一.问题描述
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array 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
. It doesn't matter what you leave beyond the new length.
二.我的解题思路
这道题首先需要理解题意,即需要以复制覆盖的方式来remove duplicate。我的思路是首先建立一个vector,然后遍历一次数组,记录下相邻元素不同的位置并且将这些位置存入vector中。比如对于[1,1,1,2,2,3],那么遍历完一次数组之后,vector中就存放着[-1,2,4,5]其中-1是人为加的,而2,4,5则代表着nums[2]!=nums[2+1]诸如此类。vector中的这些位置下标将数组nums分成了不同的段。
接下来就是遍历vector并进行移位覆盖,注意移动的位数是有叠加的。测试通过的程序如下:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
int res=0;
if(len<=2) return len;
int i=0;
vector<int> record;record.push_back(-1);
while(i+1<len){
if(nums[i]!=nums[i+1])
record.push_back(i);
i++;
}
record.push_back(len-1);
int rec_len = record.size(); int step=0;
for(int i=1;i<rec_len;i++){
int curr_step = (record[i]-record[i-1]<=2)?0:(record[i]-record[i-1]-2);
step+=curr_step;
if(curr_step==0) res+=record[i]-record[i-1]; else res+=2;
int st_idx=record[i]+1;
if(st_idx>=len) break;
int cnt=0;
while(st_idx<=record[i+1] && cnt<2){
nums[st_idx-step]=nums[st_idx];
cnt++;
st_idx++;
}
}
return res;
}
};