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.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
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.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
题目:给定一个已经排好序的数组nums
,去掉其中重复多余的元素。注意是就地删除重复项,使每个元素只出现一次并返回新的长度。所谓就地删除就是它会根据你返回的长度len
,来取nums
中前len
个元素,和实际的答案比对。
思路:假定我们新建了一个数组nums2用来存放去重后的结果(实际题目不允许,先这样假定吧),其中初值nums2[0] = nums[0]
,我们用i来更新nums2
中元素的下标。那么我们就可以这样实现数组nums
的去重:从nums
中的第二个元素即nums[1]
开始遍历整个数组,如果nums[j]
不等于nums[j-1]
,那么nums[j]
就是独特的,我们需要把它保存下来,nums2[++i] = nums[j]
。最后我们就得到了一个去重完的数组nums2
了,长度就是i+1
。
那如果我们把nums
同时看成是nums2
呢,直接nums[++i] = nums[j]
?因为j的值大于等于i,所以是完全没有问题的。这样我们就实现了就地删除重复的元素。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if(n == 0) return 0;
// last表示的是上一个非重复元素所在的位置
int last = 0;
for(int i = 1; i < n; ++i){
if(nums[i] != nums[last]){
nums[++last] = nums[i];
}
}
return last + 1;
}
};