-
Notifications
You must be signed in to change notification settings - Fork 1
/
27.remove-element.cpp
50 lines (44 loc) · 1.12 KB
/
27.remove-element.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
/*
* @lc app=leetcode id=27 lang=cpp
*
* [27] Remove Element
*/
#include <vector>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
//1.
/*
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Remove Element.
Memory Usage: 8.6 MB, less than 100.00% of C++ online submissions for Remove Element.
*/
int i = 0;
int n = nums.size();
while (i < n)
{
if (nums[i] == val)
{
nums[i] = nums[n - 1];
n--;
}
else
i++;
}
return n;
//2.
/*
Runtime: 4 ms, faster than 98.54% of C++ online submissions for Remove Element.
Memory Usage: 8.6 MB, less than 100.00% of C++ online submissions for Remove Element.
*/
for (int j = 0; j < nums.size(); ++j)
{
if (nums[j] != val)
{
nums[i] = nums[j];
i++;
}
}
return i;
}
};