您的位置:首页 > 其它

[LeetCode]Remove Duplicates from Sorted Array II

2014-08-03 20:33 357 查看

题目:

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

来源:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

思路:

前面是删除重复所有的,这题是保留两个,想当然的做了,结果没考虑清楚,耗时不少。

C++ AC代码:

class Solution {
public:
int removeDuplicates(int A[], int n) {
if( n < 3)
return n;
int i=0, j=1,cnt = 1;
for ( ; j<n; j++){
if( A[i] == A[j] ){
if ( cnt == 1 ){
A[++i]=A[j];
}
cnt++;
}
else{
A[++i] = A[j];
cnt = 1;
}
}
return i+1;
}
};


运行时间 88ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: