80. Remove Duplicates from Sorted Array II
# Medium
Two pointers work together. One pointer points first element, the other one points third element.
Solution 1:
Consider edge cases: less or equal than 2 elements
Remove shouldn't be existed element
Set
p1=0, p2=2
nums[p1] == nums[p2]
indicates the element is repeated 3 times, thenpop
itnums[p1] != nums[p2]
, thenp1
andp2
just move forward one step
Solution 2(faster):
Consider edge cases: less or equal than 2 elements
Set count=1, and track last element x
Move should be existed element to correct position
// Some code
class Solution {
public int removeDuplicates(int[] nums) {
int p = 0, count = 0;
for(int i = 1; i < nums.length; i ++) {
if(nums[p] == nums[i]) {
if(count == 0) {
count = 1;
nums[++p] = nums[i];
}
} else {
count = 0;
nums[++p] = nums[i];
}
}
return p+1;
}
}
Last updated
Was this helpful?