Given an integer array
nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array
nums
. More formally, if there arek
elements after removing the duplicates, then the firstk
elements ofnums
should hold the final result. It does not matter what you leave beyond the firstk
elements.Return
k
after placing the final result in the firstk
slots ofnums
.Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; }If all assertions pass, then your solution will be accepted.
给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
说明:
为什么返回数值是整数,但输出的答案是数组呢?
请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。
你可以想象内部操作如下:
Example 1:
Input: nums = [1,1,2] Output: 2, nums = [1,2,_] Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).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 k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
一些单词:
relative order:相对顺序
allocate:v.分配
modify:v.修改,修饰,调整
该题的解法用到了双指针
简单说一下解题思路,其实很巧妙,题目说是一个排序好的数组,所以我们就不用担心乱序问题,我们只需要两个指针,一个用来进行元素之间的比较,一个用来存放合适的元素就可以啦,现在看看代码。
这道题给了我一个新的解题思路,就是双指针原来可以这么用,之前我们做过一个题,也是用双指针,只不过是把两个指针分布在了数组的开头和结尾,现在确是用一个临时指针进行存储元素,达到不需要额外增加一个数组,来实现原地删除的方法,提高了空间复杂度。
class Solution{
public int removeDuplicates(int[] nums) {
int j = 0;
for(int i = 0;i < nums.length;i++){
if(i == 0 || nums[i] != nums[i - 1]){
//此处i = 0时,是为了应对i = 0的情况
nums[j] = nums[i];
}
j++;
}
return j;//返回的结果也就是j
}
}
最后附上官方的解答: