-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_elm.cpp
More file actions
33 lines (29 loc) · 995 Bytes
/
Copy pathremove_elm.cpp
File metadata and controls
33 lines (29 loc) · 995 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
/*
LeetCode: Problem 27: Remove Element
Difficulty Level: Easy
Name: Nava Nizard
Date: September 12, 2025
Programming Language: C++
Instructions: Given an integer array nums and an integer val, remove all occurrences of val in nums in-place.
The order of the elements may be changed. Then return the number of elements in nums which are not equal
to val.
Approach: Iterate through the array; when you find the target value, replace it with the
last element and shorten the array length. Otherwise, move forward. Return the new length.
*/
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int elms = nums.size();
int idx = 0;
while (idx < elms) {
if (nums[idx] == val) {
nums[idx] = nums[elms - 1];
elms--;
}
else {
idx++; //only continue if no overwrite
}
}
return elms; //number of elms not equal to val
}
};