首页 > 代码库 > Remove Duplicates from Sorted Array I&&II

Remove Duplicates from Sorted Array I&&II

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].

 

可假设A[0...k-1]是递增且无重复元素的数组,那么每次让A[i]与A[k-1]比,如果相等,则跳过,不等,则放入A[k],k++

 1 class Solution { 2 public: 3     int removeDuplicates(int A[], int n) { 4         if( !A || n<1 ) return 0; 5         int k = 1; 6         for(int i=1; i<n; ++i) 7             if( A[i] != A[k-1] ) A[k++] = A[i]; 8         return k; 9     }10 };

 

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

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

依然使用上面的方法.

 

 1 class Solution { 2 public: 3     int removeDuplicates(int A[], int n) { 4         if( !A || n<1 ) return 0; 5         int k = 1; 6         for(int i=1; i<n; ++i) 7             if( A[i] != A[k-1] ) A[k++] = A[i]; //A[i]与A[k-1]不等,那么肯定可以放进 8             else if( A[i] == A[k-1] && ( k<2 || A[i] != A[k-2]) )  //A[i]与A[k-1]相等,但不与A[k-2]相等,说明不足2个,那么可以放进 9                 A[k++] = A[i];10         return k;11     }12 };

 

Remove Duplicates from Sorted Array I&&II