|
| 1 | +# 27. Remove Element |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +Given an integer array `nums` and an integer `val`, remove all occurrences of `val` **in-place**. The order of the elements may be changed. Then return **the number of elements in `nums` which are not equal to `val`**. |
| 6 | + |
| 7 | +Consider the number of elements in `nums` which are not equal to `val` to be `k`, to get accepted, you need to do the following things: |
| 8 | + |
| 9 | +- Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. |
| 10 | +- Return `k`. |
| 11 | + |
| 12 | +--- |
| 13 | + |
| 14 | +## Custom Judge: |
| 15 | + |
| 16 | +The judge will test your solution with the following code: |
| 17 | + |
| 18 | +``` |
| 19 | +int[] nums = [...]; // Input array |
| 20 | +int val = ...; // Value to remove |
| 21 | +int[] expectedNums = [...]; // The expected answer with correct length. |
| 22 | +// It is sorted with no values equaling val. |
| 23 | +
|
| 24 | +int k = removeElement(nums, val); // Calls your implementation |
| 25 | +
|
| 26 | +assert k == expectedNums.length; |
| 27 | +sort(nums, 0, k); // Sort the first k elements of nums |
| 28 | +for (int i = 0; i < actualLength; i++) { |
| 29 | + assert nums[i] == expectedNums[i]; |
| 30 | +} |
| 31 | +``` |
| 32 | + |
| 33 | +If all assertions pass, then your solution will be accepted. |
| 34 | + |
| 35 | +--- |
| 36 | + |
| 37 | +## Examples |
| 38 | + |
| 39 | +### Example 1: |
| 40 | + |
| 41 | +**Input:** |
| 42 | +``` |
| 43 | +nums = [3,2,2,3], val = 3 |
| 44 | +``` |
| 45 | +**Output:** |
| 46 | +``` |
| 47 | +2, nums = [2,2,_ ,_] |
| 48 | +``` |
| 49 | +**Explanation:** |
| 50 | +Your function should return `k = 2`, with the first two elements of `nums` being `2`. |
| 51 | +It does not matter what you leave beyond the returned `k` (hence they are underscores). |
| 52 | + |
| 53 | +--- |
| 54 | + |
| 55 | +### Example 2: |
| 56 | + |
| 57 | +**Input:** |
| 58 | +``` |
| 59 | +nums = [0,1,2,2,3,0,4,2], val = 2 |
| 60 | +``` |
| 61 | +**Output:** |
| 62 | +``` |
| 63 | +5, nums = [0,1,4,0,3,_ ,_ ,_] |
| 64 | +``` |
| 65 | +**Explanation:** |
| 66 | +Your function should return `k = 5`, with the first five elements of `nums` containing `0, 0, 1, 3, and 4`. |
| 67 | +Note that the five elements can be returned in **any order**. |
| 68 | +It does not matter what you leave beyond the returned `k` (hence they are underscores). |
| 69 | + |
| 70 | +--- |
| 71 | + |
| 72 | +## Constraints |
| 73 | + |
| 74 | +- `0 <= nums.length <= 100` |
| 75 | +- `0 <= nums[i] <= 50` |
| 76 | +- `0 <= val <= 100` |
0 commit comments