#27
Remove Element
pupil · 440 · lc easy +26 · verified · 61.4% accepted · 4,996 likes · top 61%
Description
Remove every occurrence of val from integer array nums in-place, allowing the order of remaining elements to change. Return k, the number of elements not equal to val, and place those elements in the first k slots. Entries beyond index k do not matter.
Example 1:
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.
Example 2:
int k = removeElement(nums, val); // Calls your implementation
Example 3:
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];
}
Example 4:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 5:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
Code
1
2
3