-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_element.cpp
More file actions
76 lines (60 loc) · 1.45 KB
/
Copy pathremove_element.cpp
File metadata and controls
76 lines (60 loc) · 1.45 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
Remove Element
Given an array and a value, remove all instances of that value
in place and return the new length.
The order of elements can be changed.
It doesn't matter what you leave beyond the new length.
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int removeElement(int A[], int n, int elem)
{
if (n <= 0)
return n; //
if (n == 1)
return A[0] == elem ? 0 : 1;
int start = 0, end = n - 1;
while (start < end) {
if (A[start] != elem) {
start++;
} else if (A[end] == elem) {
end--;
} else {
swap(A[start], A[end]);
start++;
end--;
}
}
return start + (A[start] == elem ? 0 : 1); //
}
int removeElement2(int A[], int n, int elem)
{
int i = 0, j = 0;
while (j < n) {
if (A[j] != elem) A[i++] = A[j];
j++;
}
return i;
}
int removeElement3(int A[], int n, int elem)
{
int idx = 0;
for (int i = 0; i < n; i++) {
if (A[i] != elem) A[idx++] = A[i];
}
return idx;
}
};
int main(int argc, char *argv[])
{
int a[] = { 3, 3, 5, 4, 5 };
Solution sol;
cout << sol.removeElement(a, sizeof(a) / sizeof(int), 5) << endl;
for (auto t : a)
cout << t << ends;
return 0;
}