let nums = [1,2,2,3,3,3,4,4,4,4,5];
function removeDuplicates(nums){
let index = 0;
for(let i =1;i<nums.length;i++){
if(nums[index] != nums[i]){
nums[++index] = nums[i];
}
}
nums.length = index+1;
return index+1;
}
console.log(removeDuplicates(nums));
思路:
给你一个有序数组nums,请你原地删除重复出现的元素,使得出现次数超过俩次不包括俩次的元素只出现一次,返回删除后的数组的新长度。
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function (nums) {
let k = 2;//超过的次数
if (nums.length <= k) return nums.length;
let slow = k, fast = k;
while (fast < nums.length) {
if (nums[fast] != nums[slow - k]) {
nums[slow] = nums[fast];
slow++
}
fast++;
}
nums.length = slow;
return slow
};