-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path27.移除元素.cpp
More file actions
46 lines (41 loc) · 920 Bytes
/
27.移除元素.cpp
File metadata and controls
46 lines (41 loc) · 920 Bytes
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
/*
* @lc app=leetcode.cn id=27 lang=cpp
*
* [27] 移除元素
*/
class Solution
{
public:
int removeElement(vector<int> &nums, int val)
{
if (!nums.size())
{
return nums.size();
}
int beginIndex = 0;
int endIndex = nums.size() - 1;
while (beginIndex < endIndex)
{
if (nums[beginIndex] != val)
{
++beginIndex;
continue;
}
while (nums[endIndex] == val && endIndex > beginIndex)
{
--endIndex;
}
if (endIndex <= beginIndex)
{
break;
}
nums[beginIndex++] = nums[endIndex];
nums[endIndex--] = val;
}
while (endIndex > -1 && nums[endIndex] == val)
{
--endIndex;
}
return endIndex + 1;
}
};