26. Remove Duplicates from Sorted Array
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 ofnums
being1
and2
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 ofnums
being modified to0
,1
,2
,3
, and4
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.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy) int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
对一个已排序的数组,去掉其中的重复元素并返回新数组长度,相当于实现unique函数。多提一点,unique函数只去掉连续重复元素中的重复元素,并不保证unique之后的数组中没有重复元素,这点很重要,可以看cplusplus的例子,数组
10 20 20 20 30 30 20 20 10
unique之后的结果是
10 20 30 20 10 ? ? ? ?
前面3个重复的20只取了一个,但是隔了两个30之后又出现了两次20,此时还是取了一个20,尽管前面已经出现过20了。所以为了实现对任意数组去重的目的,需要先sort再unique。
回到本题,思路很简单,初始化两个指针i,j,i指向不重复元素的最后一个下标,j遍历数组,如果nums[j]==nums[i],说明重复,j++;否则把nums[j]放到nums[i+1],i++。完整代码如下:
class Solution {
public:
int removeDuplicates(vector<int>& nums)
{
if (nums.size() <= 1)
return nums.size();
int i = 0, j = i + 1;
while (j < nums.size()) {
if (nums[j] != nums[i]) {
nums[i + 1] = nums[j];
i++;
}
j++;
}
return i + 1;
}
};
本代码提交AC,用时32MS。
Pingback: LeetCode Remove Duplicates from Sorted Array II | bitJoy > code