Cover image for Top Interview 150 P27 Remove Element

Top Interview 150 P27 Remove Element


Timeline

timeline

2025-09-28

init

two pointers

Problem:

Simple but classic two-pointer problem, like her classic floral dress~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
using std::vector;

class Solution {
public:
int removeElement(vector<int> &nums, int val) {
int i = 0 , k = nums.size() - 1;

while (i <= k) {
if (nums[i] == val) {
std::swap(nums[i], nums[k]);
k--;

} else {
i++;
}
}

return k + 1;
}
};