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.
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:
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Example 2:
Constraints:
A common and effective technique for in-place array manipulation is using two pointers.
Here's how you can apply it:
Logic:
Implementation:
/**
* Remove the elements where `element == val`.
* Returns the index k, which has elements `element != val`
* TC: O(n)
* SC: O(n)
*
* @param nums
* @return
*/
public int removeElement(int[] nums, int val) {
int k = 0;
for(int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[k++] = nums[i];
}
}
return k;
}