您的位置:首页 > 其它

80. Remove Duplicates from Sorted Array II

2017-02-27 09:32 239 查看
Follow up for "Remove Duplicates":

What if duplicates are allowed at most twice?

For example,

Given sorted array nums = 
[1,1,1,2,2,3]
,

Your function should return length = 
5
, with the first five elements of nums being 
1
1
2
2
 and 
3
.
It doesn't matter what you leave beyond the new length.
开始的思路是:从前向后遍历,遇到前后相等的就用while跳过,代码如下:
public class Solution {
public int removeDuplicates(int[] nums) {
int len = 0, count = 0;
if (nums.length < 3) {
return nums.length;
}
for (int i = 0; i < nums.length; i ++) {
if (i != 0 && nums[i] == nums[i - 1]) {
while (i < nums.length && nums[i] == nums[i - 1])
i ++;
nums[len ++] = nums[i - 1];
}
if (i < nums.length)
nums[len ++] = nums[i];
}
return len;
}
}而后看到一种优秀的解法:
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}这样做可以推广到任意的允许x遍重复,只需把判断条件if (i < 2 || n > nums[i-2])修改成if (i < x || n > nums[i-x])。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: