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

[解题思路]

双指针问题,还是使用count来保存结果数组的大小

Remove Duplicates from Sorted Array唯一区别在添加start, end标识duplicates区间

如果当前区间中元素个数小于3,依次复制,如果≥3,则停止复制

 1 public int removeDuplicates(int[] A) {
 2         int len = A.length;
 3         if(len == 0){
 4             return len;
 5         }
 6         
 7         int start = 0, end = 0;
 8         int count = 1;
 9         for(int i = 1; i < len; i++){
10             if(A[i] == A[i - 1]){
11                 end ++;
12                 if(end - start < 2){
13                     A[count ++] = A[i];
14                 }
15                 continue;
16             } else {
17                 A[count ++] = A[i];
18                 start = i;
19                 end = i;
20             }
21         }
22         return count;
23     }
原文地址:https://www.cnblogs.com/feiling/p/3291448.html