标签:uniq vector cout from code 扩展 lse ring solution
给出排序好的一维数组,如果一个元素重复出现的次数大于两次,删除多余的复制,返回删除后数组长度,要求不另开内存空间。
献上自己丑陋无比的代码。相当于自己实现一个带计数器的unique函数
class Solution {
public:
int removeDuplicates(std::vector<int>& nums) {
if(nums.empty())
return 0;
int cnt = 0;
auto slow = nums.begin();
auto last = *nums.begin();
for(auto fast:nums){
if(cnt == 0) cnt++,slow++;
else if(cnt == 1){
if(fast == last) cnt++;
*slow = fast;
slow++;
}
else {
if(fast != last) {
cnt = 1;
*slow = fast;
slow++;
}
}
last = fast;
}
return distance(nums.begin(),slow);
}
};
学习标程后写的更简洁的版本,这样的代码扩展性更好:
class Solution {
public:
int removeDuplicates(std::vector<int>& nums) {
if(nums.size()<=2) return nums.size();
auto index = nums.begin()+2;
for(auto i = nums.begin()+2;i!=nums.end();i++){
if(*i!=*(index-2)) *index++ = *i;
}
return std::distance(nums.begin(),index);
}
};
再贴一份wiki上找来的std::unique的使用示例。感受一下vector也是可以方便的初始化的。 还有auto的使用(基本操作)
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cctype>
int main()
{
// remove duplicate elements
std::vector<int> v{1,2,3,1,2,3,3,4,5,4,5,6,7};
std::sort(v.begin(), v.end()); // 1 1 2 2 3 3 3 4 4 5 5 6 7
auto last = std::unique(v.begin(), v.end());
// v now holds {1 2 3 4 5 6 7 x x x x x x}, where 'x' is indeterminate
v.erase(last, v.end());
for (int i : v)
std::cout << i << " ";
std::cout << "\n";
}
LeetCode 80 Remove Duplicates from Sorted Array II [Array/auto] <c++>
标签:uniq vector cout from code 扩展 lse ring solution
原文地址:https://www.cnblogs.com/NeilThang/p/10305847.html