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.
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.
分析
在本题的要求中要求不仅给出移除重复数字之后数组的长度length,同时要求内存开心在O(1)。同时在Clarification中还要求数组内的值需要按照次数排列好,[0, length)还需要保证不重复。
初步分析,我们一定要在数组内进行交换,但是交换的时候又要考虑各个数字相等不相等的情况,虽然我没有把代码写出来,但是还是觉得需要进行的边界判断比较多。有一个简化问题的办法,就是将各个重复的数字简化成一个重复的数字和其他不重复的数字。
For Example:
nums = [0,0,1,1,1,2,2,3,3,4]
Convert:
nums = [0,0, 1, 0, 0, 2, 0, 3, 0, 4]
从前往后遍历,每当遇到新的数字时,记录该数字,之后每当遇到与该数字相等的数字后,都将其转化为nums[0]。这样数字就简化为重复的nums[0]和其他的不重复的数字。
接下来在进行依次遍历,每当遇到nums[i] != nums[0],就将其放到前面去。
Code
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int length = nums.size();
if (length == 0)
return 0;
int i = 0;
int tmp = nums[0];
while (i < length-1)
{
if (tmp == nums[i+1])
{
nums[i+1] = nums[0];
}
else
{
tmp = nums[i+1];
}
i++;
}
int j = 0;
for(i = 1; i < length; i ++)
{
if (nums[i] != nums[0])
{
swap(nums[i], nums[j+1]);
j ++;
}
}
return j + 1;
}
};
代码写的比较繁琐,其实代码可以做进一步的简化。但是思路还是挺简单的,总体耗时只需要两次遍历即可。
运行效率
Runtime: 24 ms, faster than 99.15% of C++ online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 10.9 MB, less than 43.30% of C++ online submissions forRemove Duplicates from Sorted Array.