Remove Element

LeetCode

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.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
  • Return k.
1def removeElement(nums: List[int], val: int) -> int:
2 k = 0
3 for i in range(len(nums)):
4 if nums[i] != val:
5 nums[k] = nums[i]
6 k += 1
7 return k
k
i
0
0
1
1
2
2
2
3
3
4
0
5
4
6
2
7
val=2
Step 1 / 7
Step 1:
Maintain k = next position to write a kept value (invariant: nums[0..k) contains no val).
Pointers: i=0, k=0
Focus: select @ [0]
val=2