Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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:
Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: 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.
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4]
Explanation: Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.
从一个有序数组中移除重复的元素,返回移除后只包含不重复元素的数组长度。
因为不能使用额外空间,所以只能在原数组上操作。要排除掉重复的元素,就需要比较两个元素是否相同,进而需要两个下标指针$i,j$,从0开始向后遍历每个元素:判断$nums[j] == nums[i]?$,如果相等就向后移动下标$j$,如果不相等就把$nums[j]$赋值给$nums[i]$,并同时向后移动下标$i,j$,最后返回数组长度$i+1$。
如下图(LeetCodeAnimation)所示:
public int removeDuplicates(int[] nums) {
int i = 0;
for (int j = 1;j < nums.length;j++) {
if (nums[i] != nums[j]) {
nums[++i] = nums[j];
}
}
return i + 1;
}
时间复杂度:$O(N)$
在原数组上操作,比较元素值是否相等,需要2个下标指针。