1 每个元素最多出现1次(双指针——快慢指针)
代码语言:javascript复制class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
// 慢指针——从第2个元素开始,表示待填补索引
int slow = 1;
for (int fast = 1; fast < nums.size(); fast )
// fast和slow-1元素对比
if (nums[fast] != nums[slow - 1]) {
nums[slow] = nums[fast];
slow ;
}
return slow;
}
};
二、每个元素最多出现2次
代码语言:javascript复制class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
if (nums.size() <= 2) return nums.size();
int slow = 2;
for (int fast = 2; fast < nums.size(); fast ) {
if (nums[slow - 2] != nums[fast]) {
nums[slow] = nums[fast];
slow ;
}
}
return slow;
}
};