Remove All Occurrences of a Value
Problem
Given an array and a target value, remove every occurrence of that value in place and return the count of values that survived. The order of remaining values should be preserved, and the slots beyond the new length don't matter. Use a slow write pointer that advances only when a kept value is copied into it, and a fast read pointer that scans the whole array.
Input
nums = [3, 2, 2, 3, 4, 3], val = 3Output
3, with nums starting [2, 2, 4, …]Three 3's are removed; the kept values 2, 2, 4 fill the front in their original order.
def remove_element(nums, val):
w = 0
for r in range(len(nums)):
if nums[r] != val:
nums[w] = nums[r]
w += 1
return w
function removeElement(nums, val) {
let w = 0;
for (let r = 0; r < nums.length; r++) {
if (nums[r] !== val) {
nums[w++] = nums[r];
}
}
return w;
}
class Solution {
public int removeElement(int[] nums, int val) {
int w = 0;
for (int r = 0; r < nums.length; r++) {
if (nums[r] != val) {
nums[w++] = nums[r];
}
}
return w;
}
}
int removeElement(vector<int>& nums, int val) {
int w = 0;
for (int r = 0; r < nums.size(); r++) {
if (nums[r] != val) {
nums[w++] = nums[r];
}
}
return w;
}