-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_element.cpp
More file actions
52 lines (49 loc) · 1.3 KB
/
Copy pathremove_element.cpp
File metadata and controls
52 lines (49 loc) · 1.3 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* Problem statement :- https://leetcode.com/problems/remove-element/description/
*/
class Solution {
public:
int removeElement_verySlow(vector<int>& nums, int val) {
sort(nums.begin(), nums.end());
int f, l, n = nums.size();
for(f = 0; f < n && nums[f] != val; f++){}
if(f > n-1) return n; //absent
for(l = f + 1; l < n && nums[l] == val; l++){}
int c = l - f;
int to = f, from = l;
while(from < n) {
nums[to] = nums[from];
to++;
from++;
}
return n - c;
}
int removeElement_slow(vector<int>& nums, int val) {
//copying "wanted" numbers
int to = 0, from = 0;
int n = nums.size();
while(from < n){
if(nums[from] != val){
nums[to] = nums[from];
to++;
}
from++;
}
return to;
}
int removeElement(vector<int>& nums, int val) {
//removing "unwanted" numbers
int n = nums.size();
int last = n-1;
int cur = 0;
while(cur <= last){
if(nums[cur] == val) {
nums[cur] = nums[last];
last--; //n--
} else{
cur++;
}
}
return last+1;
}
};