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.
这里有两个方法,都是从头到尾走一遍数组,第一种办法用了一个标志位来判断该元素是否重复两次
后面的方法很巧妙,直接用当前要判断的数与已经判断过的倒数第二个数来比较,现在有这么两种情况,最后两个数可能是2,2或2,3。现在的数可能是2或3或4,那么只要保证当前数大于倒数第二个数,当前数就可以放进已判断数组。
var removeDuplicates = function(nums) {
var num = nums.length;
if (num < 3)
return num;
var flag = false;
var tail = 0;
for (var i = 0; i < num;i++) {
if (nums[i]!==nums[i+1]&&flag) {
nums[tail++] = nums[i-1];
nums[tail++] = nums[i];
flag = false;
}else if (nums[i]!==nums[i+1]&&!flag) {
nums[tail++] = nums[i];
flag = false;
} else if (nums[i]===nums[i+1]&&!flag) {
flag = true;
}
}
return tail;
};
var removeDuplicates = function(nums) {
var num = nums.length;
if (num < 3)
return num;
var k = 2;
for(var i = 2;i<num;i++) {
if (nums[i]>nums[k-2])
nums[k++] = nums[i];
}
return k;
};