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

Solution: Two pointers ('last' and 'lastlast').

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

 

posted @ 2014-04-05 00:43  beehard  阅读(144)  评论(0编辑  收藏  举报