LeetCode刷题:80. Remove Duplicates from Sorted Array II
题目描述:
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn’t matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn’t matter what values are set beyond the returned length.
题目分析:
这道题其实很简单,题目意思就是每一个元素最多不超过两个,超过了删掉超过的部分。那实现起来就是记录每一个元素出现的次数,如果出现的次数大于2,就要把超过的删掉就OK了。
程序实现:
int removeDuplicates(vector<int>& nums) {
if(nums.empty())
return 0;
int curNum = nums[0];
int appear = 1;
int res = 1;
for(int i = 1;i<nums.size();i++){
if(nums[i] == curNum){
appear++;
if(appear < 3)
res++;
else{
nums.erase(nums.begin()+i);
i--;
}
}else{
curNum = nums[i];
appear = 1;
res++;
}
}
return res;
}
测试结果:
分析:只快过18.48%的人,这显然不是我所追求的,男人,就是要快!仔细检查上面的代码,其实耗时的不多,显然只是O(1),问题可能就出在删除语句那里nums.erase(nums.begin()+i);
这部分其实还是需要遍历一遍数组的,所以花费了一点时间。
改进:
可以试着标记出现多余数字的位置,然后把后面的不多余的位置上的数字换过来。
举个例子:
我们用两个变量mov,i,分别表示遍历过且最大数目不超过2的元素的下标和遍历过的数组下标
第一步,也就是刚开始的时候,mov和i是相等的
第二步的时候,1这个元素已经出现了四次,此时i还是继续增加的,但mov停在1的数目等于2的下标
第三步,i发现了一个新元素,这个时候,mov就可以向右移动一下,此时,还要改变移动后的位置的元素,也就是把1改成2,其实交换也行,但是交换要3步,赋值只用一步,还是赋值1快。
第四步,发现新元素,mov向右移动并改变该位置的元素
第五步也是如此。
最后,0到mov这一段的切片就是“去重”后的数组。
改进后的代码:
int removeDuplicates(vector<int>& nums) {
if(nums.empty())
return 0;
int curNum = nums[0];
int appear = 1;
int change = 0;
int mov = 1;
for(int i = 1;i<nums.size();i++){
if(nums[i] == curNum){
appear++;
if(appear == 2){
nums[mov] = nums[i];
mov++;
}
else{
change++;
}
}else{
curNum = nums[i];
appear = 1;
nums[mov] = nums[i];
mov++;
}
}
return (nums.size() - change);
}
测试结果:
果然快了很多!