27. Remove Element
Problem
Remove every occurrence of val from nums in place and return the number k of remaining values; the first k slots must hold them in any order.
Example: nums = [0,1,2,2,3,0,4,2], val = 2 → 5, first five slots 0,1,3,0,4 in any order
Copy every element not equal to val to the write pointer k.
Complexity: O(n).
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for x in nums:
if x != val:
nums[k] = x
k += 1
return k
a = [0, 1, 2, 2, 3, 0, 4, 2]
k = Solution().removeElement(a, 2)
assert k == 5 and sorted(a[:k]) == [0, 0, 1, 3, 4]
a = [3, 2, 2, 3]
k = Solution().removeElement(a, 3)
assert k == 2 and sorted(a[:k]) == [2, 2]
a = [1]
k = Solution().removeElement(a, 1)
assert k == 0
class Solution {
public int removeElement(int[] nums, int val) {
int k = 0;
for (int x : nums) if (x != val) nums[k++] = x;
return k;
}
}
func removeElement(nums []int, val int) int {
k := 0
for _, x := range nums {
if x != val {
nums[k] = x
k++
}
}
return k
}