您的位置:首页 > 其它

LeetCode Remove Duplicates from Sorted Array II

2015-02-15 23:21 302 查看


Remove Duplicates from Sorted Array II

Total Accepted: 32492 Total
Submissions: 105872My 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: