Remove Duplicates from Sorted Array II [LeetCode]

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

Solution:

 1     int removeDuplicates(int A[], int n) {

 2         if(n <= 2)

 3             return n;

 4         int pre = A[0];

 5         int same_count = 0;

 6         int rm_count = 0;

 7         int i = 1;

 8         while(i < n - rm_count) {

 9             if(A[i] == pre){

10                 same_count ++;

11             }else{

12                 pre = A[i];

13                 same_count  = 0;

14             }

15             

16             if(same_count >= 2){

17                 //remove A[i]

18                 for(int j = i + 1; j < n - rm_count; j ++)

19                     A[j - 1] = A[j];

20                 rm_count ++;

21             }else{

22                 i ++;

23             }

24         }

25         return n - rm_count;

26     }

 

你可能感兴趣的:(LeetCode)