Deleting from the middle of an array is slow because every later element has to shift. A common trick is to not shrink the list at all: overwrite the values you want to keep at the front and return how many there are. Callers then only read the first k slots.
Given a list nums and an integer val, remove every occurrence of val in place. Return the number k of remaining elements. After your function returns, the first k positions of nums must hold exactly the kept values (in any order); whatever sits beyond position k does not matter.
Examples
Input: nums = [3, 2, 2, 3], val = 3
Output: 2
After: the first 2 slots of nums contain 2 and 2
Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2
Output: 5
After: the first 5 slots of nums contain 0, 0, 1, 3, 4 in some order
Constraints
0 <= len(nums) <= 1000- Modify
numsin place; the tests readnums[:k]after the call.
Goals
- Overwrite unwanted values in place and report how many elements remain
- Recognise the 'return the new length' convention used by many array problems