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);
}
本文介绍了一种在原地删除排序数组中重复元素的方法,使用双指针技巧实现,无需额外空间,满足O(1)内存限制。通过慢指针定位目标位置,快指针遍历数组,当两指针指向不同元素时,将快指针元素复制到慢指针位置,并更新慢指针。
403

被折叠的 条评论
为什么被折叠?



