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

典型的两指针问题

两个指针指向初始位置,一个指针i开始遍历,记录出现相同数的个数

如果遍历的指针i等于其前面的指针index且cnt个数超过两个,则继续移动遍历的指针

如果遍历的指针i等于其前面的指针index且cnt个数恰好为2,则更新index指针

如果遍历的指针不等于其前面的指针index,则出现相同的数,更新index指针,且清零计数器

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int removeDuplicates(int A[], int n){
    if(n < 3) return n;
    int index = 0, cnt = 0;
    for(int i = 1; i < n; ++ i){
        if(A[i] == A[index] && cnt < 2){
            A[++index] = A[i];
            cnt = 2;
        }else if(A[i] != A[index]){
            A[++index] = A[i];
            cnt =0 ;
        }
    }
    return index+1;
}

int main(){
    int A[] = {1,1,1,2,2,3};
    cout<<removeDuplicates(A,6)<<endl;
}

 

posted @ 2014-06-21 17:46  OpenSoucre  阅读(161)  评论(0编辑  收藏  举报