01 · Question
Given nums and val, remove every val in-place and return the new length k. Only the first k positions matter after the operation.
02 · Analysis
Use a read pointer i and a write pointer k:
iscans every value.- If
nums[i] != val, write it tonums[k]and advancek. - The invariant is:
nums[0:k]contains exactly the values we are keeping.
The point: treat the input array as the output buffer and compact the kept values into its front.
Complexity: time and extra space.