Algorithm: efficient way to remove duplicate integers from an array

前端 未结 30 2602
离开以前
离开以前 2020-11-22 16:03

I got this problem from an interview with Microsoft.

Given an array of random integers, write an algorithm in C that removes duplicated numbers an

30条回答
  •  情深已故
    2020-11-22 16:39

    The return value of the function should be the number of unique elements and they are all stored at the front of the array. Without this additional information, you won't even know if there were any duplicates.

    Each iteration of the outer loop processes one element of the array. If it is unique, it stays in the front of the array and if it is a duplicate, it is overwritten by the last unprocessed element in the array. This solution runs in O(n^2) time.

    #include 
    #include 
    
    size_t rmdup(int *arr, size_t len)
    {
      size_t prev = 0;
      size_t curr = 1;
      size_t last = len - 1;
      while (curr <= last) {
        for (prev = 0; prev < curr && arr[curr] != arr[prev]; ++prev);
        if (prev == curr) {
          ++curr;
        } else {
          arr[curr] = arr[last];
          --last;
        }
      }
      return curr;
    }
    
    void print_array(int *arr, size_t len)
    {
      printf("{");
      size_t curr = 0;
      for (curr = 0; curr < len; ++curr) {
        if (curr > 0) printf(", ");
        printf("%d", arr[curr]);
      }
      printf("}");
    }
    
    int main()
    {
      int arr[] = {4, 8, 4, 1, 1, 2, 9};
      printf("Before: ");
      size_t len = sizeof (arr) / sizeof (arr[0]);
      print_array(arr, len);
      len = rmdup(arr, len);
      printf("\nAfter: ");
      print_array(arr, len);
      printf("\n");
      return 0;
    }
    

提交回复
热议问题