您的位置:首页 > 其它

[leetcode] Remove Duplicates from Sorted Array II

2013-04-03 20:21 387 查看
Remove Duplicates from Sorted Array IIApr
19 '12

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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<1) return 0;
int i=1;
int cnt=0;
while(i<n)
{
if(A[i]==A[i-1])
{
cnt++;
if(cnt<2) i++;
else
{
if(i==n-1) n--;
else
{
for(int j=i+1; j<n; j++)
{
A[j-1]=A[j];
}
n--;
}
}
}
else
{
cnt=0;
i++;
}
}
return n;
}
};
另一种解法是设置两个下标,用state表明当前节点是第几次出现,若不是连续第3次出现,则将后面下标的节点搬到前面下标记录的位置上去。

class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ans = 0;
int state;
for(int i = 0;i < n;i++)
{
if(i == 0 || A[i] != A[i-1])
{
A[ans++] = A[i];
state = 1;
}
else if(state == 1)
{
state++;
A[ans++] = A[i];
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: