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

Remove Duplicates from Sorted Array II

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( n <= 2 ) { return n; } 5         int pos = 1; 6         for( int i = 2; i < n; ++i ) { 7             if( A[i] != A[pos-1] ) { A[++pos] = A[i]; } 8         } 9         return pos+1;10     }11 };

 

Remove Duplicates from Sorted Array II