LeetCode

Remove Duplicates from Sorted Array

2013.12.7 03:29

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

Solution:

  The array is sorted, so duplicates must be in a consecutive group. Here I used two pointers, one to scan the array, the other to record the unique value. Everytime a unique value is found, record it. The rest of the duplicate values are discarded and overwritten.

  Time complexity is O(n), space complexity is O(1).

Accepted code:

 1 //#define __MAIN__
 2 #include <cstdio>
 3 #include <cstdlib>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     int removeDuplicates(int A[], int n) {
 9         // Note: The Solution object is instantiated only once and is reused by each test case.
10         int i, j, k;
11 
12         i = 0;
13         k = 0;
14         while(i < n){
15             j = i + 1;
16             while(j < n && A[i] == A[j]){
17                 ++j;
18             }
19             A[k] = A[i];
20             ++k;
21             i = j;
22         }
23 
24         return k;
25     }
26 };
27 
28 #ifdef __MAIN__
29 int main()
30 {
31     Solution sol;
32     int A[] = {1};
33     const int n = sizeof(A) / sizeof(int);
34     int len;
35 
36     len = sol.removeDuplicates(A, n);
37     printf("%d
", len);
38     for(int i = 0; i < len; ++i){
39         printf("%d ", A[i]);
40     }
41     printf("
");
42 
43     return 0;
44 }
45 #endif
原文地址:https://www.cnblogs.com/zhuli19901106/p/3462405.html