-
Notifications
You must be signed in to change notification settings - Fork 9
/
removeElement.cpp
64 lines (57 loc) · 1.29 KB
/
removeElement.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
53
54
55
56
57
58
59
60
61
62
63
64
/**
* leetcode: remove element
* easy
*/
#include <cstdio>
#include <vector>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
return method1(nums, val);
}
private:
int method1(vector<int>& nums, int val) {
printArray(nums);
int k = 0;
for (int i=0; i<nums.size(); ++i) {
if (nums[i] != val) {
swap(nums, i, k);
k++;
} else {
}
}
printArray(nums);
printf("result--> %d\n", k);
return k;
}
int method2(vector<int>& nums, int val) {
int k = 0;
for (int i=0; i<nums.size(); ++i) {
if (nums[i] != val) {
swap(nums, i, k);
k++;
} else {
}
}
return k;
}
void swap(vector<int>& nums, int i, int k) {
int temp = nums[k];
nums[k] = nums[i];
nums[i] = temp;
}
void printArray(vector<int>& nums) {
for (int i=0; i<nums.size(); ++i) {
printf("%d,", nums[i]);
}
printf("\n");
}
};
int main() {
Solution sln;
int array[8] = {1, 0, 0, 2, 3, 5, 0, 4};
vector<int> nums(array, array+8);
sln.removeElement(nums, 0);
return 0;
}