26. 删除有序数组中的重复项 - 力扣(LeetCode)
快慢指针,慢的指针去追赶快的指针,相等时也就是追到时,快指针移动向前
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int s = 1, q = 1;
int n = nums.size();
while(q < n)
{
if(nums[q] != nums[q-1]){
nums[s] = nums[q];
s++;
}
q++;
}
return s;
}
};
80. 删除有序数组中的重复项 II - 力扣(LeetCode)
双指针
快指针用来跳过重复>2的元素,替换;
慢指针用来记录最终值;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if(n <= 2)
return n;
int f = 2, s = 2;
while(f < n){
if(nums[s-2] != nums[f]){
nums[s] = nums[f];
s++;
}
f++;
}
return s;
}
};