-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path27.移除元素.cpp
52 lines (45 loc) · 948 Bytes
/
27.移除元素.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* @lc app=leetcode.cn id=27 lang=cpp
*
* [27] 移除元素
*/
// @lc code=start
class Solution
{
public:
int removeElement(vector<int> &nums, int val)
{
// int slow = 0;
// int fast = 0;
// int n = nums.size();
// for (; fast < n; ++fast)
// {
// if (nums[fast] != val)
// {
// nums[slow++] = nums[fast];
// }
// }
// return slow;
int left = 0;
int right = nums.size() - 1;
while (left <= right)
{
if (nums[left] != val)
{
++left;
continue;
}
else if (nums[right] == val)
{
--right;
continue;
}
else
{
std::swap(nums[left++], nums[right]);
}
}
return left;
}
};
// @lc code=end