Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn’t matter what you leave beyond the returned length.
给出一个排序好的数组,让在原数组中去掉重复元素,即原地替换,不要新建一个数组
思路:
双指针,慢指针留在需要替换元素的位置,快指针遍历数组
两指针指向的元素相同的时候,快指针右移,不同的时候,慢指针右移,同时替换元素,然后快指针继续遍历
public int removeDuplicates(int[] nums) {
int n = nums.length;
int left = 0;
for(int right = 1; right < n; right ++) {
if(nums[left] == nums[right]) continue;
nums[++left] = nums[right];
}
return (left+1);
}