LeetCode OJ 80. Remove Duplicates from Sorted Array II
阿新 • • 發佈:2018-04-18
mat new pan turn beyond etc 變量賦值 mos UNC
題目
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.
解答
這題又是一遍AC。。。只能說LeetCode上水題有點多,這居然都是Medium難度。。。
拿一個變量計數一下重復次數就可以了,每次遇到新的數就將這個變量賦值為1,如果這個變量達到2且遇到和之前重復的數,就移除。
下面是AC的代碼:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0){
return 0;
}
int last = nums[0];
int count = 1;
int dup = 1;
for(vector<int >::iterator iter = nums.begin() + 1; iter != nums.end(); iter++){
if(*iter == last){
if(dup < 2){
dup++;
count++;
}
else{
nums.erase(iter);
iter--;
}
}
else {
dup = 1;
count++;
last = *iter;
}
}
return count;
}
};
118
LeetCode OJ 80. Remove Duplicates from Sorted Array II