https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
思路:定义快慢指针,初始
s
l
o
w
=
f
a
s
t
=
0
slow=fast=0
slow=fast=0,如果
n
u
m
s
[
f
a
s
t
]
=
n
u
m
s
[
s
l
o
w
]
nums[fast]=nums[slow]
nums[fast]=nums[slow],那么递增
f
a
s
t
fast
fast,不然就令
n
u
m
s
[
s
l
o
w
+
1
]
=
n
u
m
s
[
f
a
s
t
]
nums[slow+1]=nums[fast]
nums[slow+1]=nums[fast],然后再递增
s
l
o
w
、
f
a
s
t
slow、fast
slow、fast即可。如果题目需要真正删除这些元素,我们可以先做上述操作,然后再把从
s
l
o
w
+
1
slow+1
slow+1到末尾的元素删除掉。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int slow=0,fast=0,n=nums.size();
if(!n)
return 0;
while(fast<n)
{
if(nums[fast]==nums[slow])
++fast;
else
nums[++slow]=nums[fast++];
}
return slow+1;
}
};