-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove_element.cpp
29 lines (23 loc) · 954 Bytes
/
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
// Class definition for the solution.
class Solution {
public:
// Function to remove all occurrences of a given value from a vector.
// Returns the new size of the vector after removals.
int removeElement(vector<int>& nums, int val) {
// Start iterating over the vector from the beginning.
for (size_t i = 0; i < nums.size(); ) { // Notice there's no increment in the loop header.
// Check if the current element is equal to the value we want to remove.
if (nums[i] == val) {
// If it is, erase the current element from the vector.
nums.erase(nums.begin() + i);
// Since the element is removed, we don't increment 'i' here.
}
else {
// If the current element is not equal to the value, move to the next element.
++i;
}
}
// Return the new size of the vector after removals.
return nums.size();
}
};