- 使用 STL 的删除方法
C++:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if ( nums.empty() ) {
return 0;
}
int size = nums.size();
int lastResult = nums[0];
for ( int i = 1; i < nums.size(); ) {
if ( nums[i] == lastResult ) {
--size;
nums.erase(nums.begin() + i);
} else {
lastResult = nums[i];
++i;
}
}
return size;
}
};
2,双指针法
C++:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if ( nums.empty() ) {
return 0;
}
int i = 0;
for ( int j = 1; j < nums.size(); ++j ) {
if ( nums[i] != nums[j] ) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
};
网友评论