-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveDulpicatesII.cpp
More file actions
37 lines (34 loc) · 1.23 KB
/
removeDulpicatesII.cpp
File metadata and controls
37 lines (34 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <vector>
using namespace std;
class Solution
{
public:
/*
* 使用快慢指针进行遍历,直接返回慢指针所在位置,这个位置就是所需要的length长度
* 快指针就直接遍历所有数组下标
*/
int removeDuplicates(vector<int> &nums)
{
if (nums.size() == 0) return 0;
// 下一个待写入的有效位置
int slow = 1;
int counter = 1;
int currentElem = nums[0];
for (int fast = 1;fast < nums.size();fast++){
// 遇到不同元素了,直接归零
if (currentElem != nums[fast]){
counter = 1;
currentElem = nums[fast];
}
else
counter++;
// 小于2的时候,慢指针也跟着移动,并替换元素。至于先++还是先替换,slow在运行中充当靠后一位的索引,当前位置就是待替换的位置,这样就可以直接返回slow,因为他可以充当题目要求的返回数组元素个数
if (counter <= 2){
nums[slow] = nums[fast];
slow++;
}
// 大于2了,就直接不加了,只让快指针移动
}
return slow;
}
};