Question
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Analysis
三种情况
- 如果nums[end] == val,end–,直到nums[end] != val
- 如果nums[start] == val, 交换nums[start] and nums[end], start++; end–
- nums[start] != val, start++, 继续循环
Java only pass by value. Java does not pass by reference
Complexity
Worst Case:
All numbers are target num. Time Complexity is O(n)
It is In-Place use O(1) to swap
Solution
1 |
public int (int[] nums, int val) {· |
近期评论