您的位置:首页 > 其它

[LeetCode] Remove Duplicates from Sorted Array II

2014-06-16 09:46 246 查看
题目:

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 <= 1) {
return n;
}
int num = 1;
int cur = 0;
for(int i = 1; i < n; i++) {
if(A[i] == A[cur]) {
if(num < 2) {
A[++cur] = A[i];
num++;
}
else {
continue;
}
}
else {
num = 1;
A[++cur] = A[i];
}
}
return cur + 1;
}
};


思路:相比“Remove Duplicates from Sorted Array”,在遍历的过程中加了一个计数器,保证最多重复次数为2.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: