-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveElement.cpp
More file actions
37 lines (33 loc) · 853 Bytes
/
Copy pathremoveElement.cpp
File metadata and controls
37 lines (33 loc) · 853 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
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
/*
Removes all instances of 'val' in-place by swapping with end elements.
Returns the new length of the array after removal.
Uses two pointers: left (i) and right (c), with k counting removals.
*/
int removeElement(vector<int>& nums, int val) {
int i = 0;
int c = nums.size() - 1;
int k = 0;
while (i <= c) {
if (nums[c] == val) {
c--;
k++;
continue;
}
if (nums[i] == val) {
int tmp = nums[i];
nums[i] = nums[c];
nums[c] = tmp;
k++;
c--;
}
i++;
}
return nums.size() - k;
}
};