LeetCode - 80. Remove Duplicates from Sorted Array II
Thoughts:
I choose two pointer to solve this problem,
when I need to compare two values and the array is sorted.
The time complexity is O(n) for the iteration.
Thoughts visuzlization:
nums = [0,0,1,1,1,1,2,3,3]
i is right pointer, represented the cusor of current element
k is left pointer, represented the cursor for checking the previous two elements with current value
the first two elements are not important, because no matter they are same or not, they are always valid
if nums[i] is not equal to nums[k-1] or nums[k-2], it means nums[k] won't be the third same value
and I can replace nums[k] with nums[i], then move k pointer to right
in the end, always move i pointer to right
[0,0,1,1,1,1,2,3,3]
i
k
[0,0,1,1,1,1,2,3,3]
i
k
[0,0,1,1,1,1,2,3,3]
i
k
[0,0,1,1,1,1,2,3,3]
i
k
[0,0,1,1,1,1,2,3,3]
i
k
[0,0,1,1,2,1,2,3,3]
i
k
[0,0,1,1,2,1,2,3,3]
i
k
[0,0,1,1,2,3,2,3,3]
i
k
[0,0,1,1,2,3,2,3,3]
i
k
[0,0,1,1,2,3,3,3,3]
i
k
Code:
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function (nums) {
let k = 2;
for (let i = 2; i < nums.length; i++) {
if (nums[i] !== nums[k - 1] || nums[i] !== nums[k - 2]) {
nums[k] = nums[i];
k++;
}
}
return k;
};
Reference
Copyright © 2024 | All rights reserved.