【双指针】删除重复项-带优化思路
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<=1) return nums.size();
int p=0,q=1;
while(q<nums.size()){
if(nums[q]==nums[p]){
q++;
continue;
}
nums[p+1]=nums[q];
p++;
}
return p+1;
}
};
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<=1) return nums.size();
int p=0,q=1;
while(q<nums.size()){
if(nums[q]==nums[p]){
q++;
continue;
}
if(q-p>1) nums[p+1]=nums[q]; /优化重复操作
p++;
}
return p+1;
}
};
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() < 2) return nums.size();
int j = 0;
for (int i = 1; i < nums.size(); i++)
if (nums[j] != nums[i]) nums[++j] = nums[i];
return ++j;
}
};