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

思路:这道题与Remove Duplicates from Sorted Array思路差不多吧,就是在记录相等元素的时候有些变化,当相等元素超过两个的时候直接跳过,后面的数不作为记录。

class Solution {

public:

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

        int nLength=0;

        if(A==NULL || n==0)

            return 0;

        int count=1;

        int cur=A[0];

        for(int i=1;i<n;i++)

        {

            if(A[i]==cur)

            {

                if(++count>2)

                    continue;

            }

            else

            {

                cur=A[i];

                count=1;

            }

            nLength++;

            A[nLength]=cur;

        }

        return nLength+1;

    }

};

 

 

 

 

你可能感兴趣的:(remove)