|
| 1 | +# 27. Remove Element |
| 2 | + |
| 3 | +Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [in-place](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return the number of elements in `nums` which are not equal to `val`. |
| 4 | + |
| 5 | +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: |
| 6 | + |
| 7 | +- 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`. |
| 8 | +- Return `k`. |
| 9 | + |
| 10 | +### Custom Judge: |
| 11 | + |
| 12 | +The judge will test your solution with the following code: |
| 13 | + |
| 14 | +``` |
| 15 | +int[] nums = [...]; // Input array |
| 16 | +int val = ...; // Value to remove |
| 17 | +int[] expectedNums = [...]; // The expected answer with correct length. |
| 18 | +// It is sorted with no values equaling val. |
| 19 | +
|
| 20 | +int k = removeElement(nums, val); // Calls your implementation |
| 21 | +
|
| 22 | +assert k == expectedNums.length; |
| 23 | +sort(nums, 0, k); // Sort the first k elements of nums |
| 24 | +for (int i = 0; i < actualLength; i++) { |
| 25 | +assert nums[i] == expectedNums[i]; |
| 26 | +} |
| 27 | +``` |
| 28 | + |
| 29 | +If all assertions pass, then your solution will be accepted. |
| 30 | + |
| 31 | +### Example 1: |
| 32 | + |
| 33 | +> <span style="color: white;">Input: </span>nums = [3, 2, 2, 3], val = 3<br> |
| 34 | +> <span style="color: white;">Output: </span>2, nums = [2, 2, _, _]<br> |
| 35 | +> <span style="color: white;">Explanation: </span>Your function should return k = 2, with the first two elements of nums being 2.<br> |
| 36 | +> It does not matter what you leave beyond the returned k (hence they are underscores). |
| 37 | +
|
| 38 | +### Example 2: |
| 39 | + |
| 40 | +> <span style="color: white;">Input: </span>nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2<br> |
| 41 | +> <span style="color: white;">Output: </span>5, nums = [0, 1, 4, 0, 3, _, _, _]<br> |
| 42 | +> <span style="color: white;">Explanation: </span>Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.<br> |
| 43 | +Note that the five elements can be returned in any order.<br> |
| 44 | +It does not matter what you leave beyond the returned k (hence they are underscores). |
| 45 | + |
| 46 | +### Constraints: |
| 47 | + |
| 48 | +- `0 <= nums.length <= 100` |
| 49 | +- `0 <= nums[i] <= 50` |
| 50 | +- `0 <= val <= 100` |
0 commit comments