LeetCode Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array II

  Total Accepted: 32492  Total Submissions: 105872 My Submissions
Question  Solution 

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

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n<=2)return n;
        int index=0;
        map<int,int>m;
        for(int i=0;i<n;++i)
        {
            m[A[i]]++;
            if(m[A[i]]<=2)//只记录两次以内的
                A[index++]=A[i];
        }
        return index;
    }
};
164 / 164 test cases passed.
Status: Accepted
Runtime: 36 ms

代码二:

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n<=2)return n;
		int index=0;
		int c=1;
		for(int i=1;i<n;++i)
		{
			if(A[i]!=A[i-1])
			{
				A[++index]=A[i];
				c=1;
			}
			else if(A[i]==A[i-1]&&c<2){
				c++;
					A[++index]=A[i];
			}
		}
		return index+1;
    }
};

164 / 164 test cases passed.
Status: Accepted
Runtime: 20 ms

你可能感兴趣的:(LeetCode,remove,Duplicates,FR)