您的位置:首页 > 其它

leetcode -- Remove Duplicates from Sorted Array II

2013-08-30 14:57 375 查看
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]
.

[解题思路]

双指针问题,还是使用count来保存结果数组的大小

Remove Duplicates from Sorted Array唯一区别在添加start, end标识duplicates区间

如果当前区间中元素个数小于3,依次复制,如果≥3,则停止复制

public int removeDuplicates(int[] A) {
int len = A.length;
if(len == 0){
return len;
}

int start = 0, end = 0;
int count = 1;
for(int i = 1; i < len; i++){
if(A[i] == A[i - 1]){
end ++;
if(end - start < 2){
A[count ++] = A[i];
}
continue;
} else {
A[count ++] = A[i];
start = i;
end = i;
}
}
return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: