Delete duplicate items from sorted array
Address: leetcode-cn.com/problems/re…
Don’t splice
var removeDuplicates = function(nums) {
let a=nums[0];
for(let i = 1;i<nums.length;i++)
{
if(a==nums[i])
{
nums.splice(i,1);
i=i-1;
}
else{
a=nums[i];
}
}
};
Copy the code
This code does not have the brain, or take a taste of the big guy’s code.
Var removeDuplicates = function(nums) {return nums.length if (nums.length < 2) return nums.length; // set the slow pointer to the first item of the array let left = 0; // let right = 1; While (right < nums.length) {if (nums[left] === nums[right]) {// If (nums[left] === nums[right]) { Nums [left + 1] = nums[right]; nums[left + 1] = nums[right]; right++; left++; Return left + 1; return left + 1; };Copy the code
Two-pointer method, very practical.
Below is the sliding window:
var removeDuplicates = function(nums) {
let idx = 0, nowIdx, pass = 0;
while(idx + pass + 1 < nums.length){
nowIdx = idx + pass + 1;
if(nums[idx] === nums[nowIdx]){
pass++;
}else{
idx++;
[nums[idx], nums[nowIdx]] = [nums[nowIdx], nums[idx]];
}
}
return idx + 1;
};
Copy the code
At the beginning of the code, I have been struggling, their array is still in the back, the result of a good look at the output of the question, just understand, the back of the direct output.