Open
Description
方法1 快慢指针
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
if(nums.length == 0){return 0;}
let slow = 0, fast = 1;
while(fast < nums.length){
if(nums[fast] != nums[slow]){
slow = slow + 1;
nums[slow] = nums[fast];
}
fast = fast + 1;
}
return slow + 1;
};
方法2 通过统计重复的个数, 反向计算需要修改的位置
function removeDuplicates(nums) {
let count = 0;//重复的数字个数
for (let right = 1; right < nums.length; right++) {
if (nums[right] === nums[right - 1]) {
//如果有重复的,count要加1
count++;
} else {
//如果没有重复,后面的就往前挪, 覆盖
nums[right - count] = nums[right];
}
}
//数组的长度减去重复的个数
return nums.length - count;
}