Remove all occurrences of a target value from an array in-place and return the new length.
You are given an integer array nums and an integer val. Remove every occurrence of val from nums in-place so that the remaining elements occupy the beginning of the array.
The relative order of the remaining elements does not need to be preserved unless stated otherwise. Return the number of elements left after removal.
After the function finishes, only the first returned elements of nums should be considered valid.
Input Format
- An integer array
nums - An integer
valto remove
Output Format
Return an integer representing the number of elements in nums that are not equal to val.
Constraints
- Modify the array in-place using extra space when possible.
- The order of kept elements may be changed unless the implementation chooses to preserve it.
- Assume
numscan be empty.
Example 1
Input
nums = [3,2,2,3], val = 3
Output
2
Explanation
Remove all 3s. The first two positions of the array can contain the remaining values, such as [2,2].
Example 2
Input
nums = [0,1,2,2,3,0,4,2], val = 2
Output
5
Explanation
After removing 2s, five elements remain, for example [0,1,3,0,4].
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.