|
| 1 | +### [27\. Remove ElementCopy for Markdown](https://leetcode.com/problems/remove-element/) |
| 2 | + |
| 3 | +Difficulty: **Easy** |
| 4 | + |
| 5 | + |
| 6 | +Given an array _nums_ and a value _val_, remove all instances of that value and return the new length. |
| 7 | + |
| 8 | +Do not allocate extra space for another array, you must do this by **modifying the input array** with O(1) extra memory. |
| 9 | + |
| 10 | +The order of elements can be changed. It doesn't matter what you leave beyond the new length. |
| 11 | + |
| 12 | +**Example 1:** |
| 13 | + |
| 14 | +``` |
| 15 | +Given nums = [3,2,2,3], val = 3, |
| 16 | +
|
| 17 | +Your function should return length = 2, with the first two elements of nums being 2. |
| 18 | +
|
| 19 | +It doesn't matter what you leave beyond the returned length. |
| 20 | +``` |
| 21 | + |
| 22 | +**Example 2:** |
| 23 | + |
| 24 | +``` |
| 25 | +Given nums = [0,1,2,2,3,0,4,2], val = 2, |
| 26 | +
|
| 27 | +Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. |
| 28 | +
|
| 29 | +Note that the order of those five elements can be arbitrary. |
| 30 | +
|
| 31 | +It doesn't matter what values are set beyond the returned length.``` |
| 32 | +
|
| 33 | +**Clarification:** |
| 34 | +
|
| 35 | +Confused why the returned value is an integer but your answer is an array? |
| 36 | +
|
| 37 | +Note that the input array is passed in by **reference**, which means modification to the input array will be known to the caller as well. |
| 38 | +
|
| 39 | +Internally you can think of this: |
| 40 | +
|
| 41 | +``` |
| 42 | +// nums is passed in by reference. (i.e., without making a copy) |
| 43 | +int len = removeElement(nums, val); |
| 44 | + |
| 45 | +// any modification to nums in your function would be known by the caller. |
| 46 | +// using the length returned by your function, it prints the first len elements. |
| 47 | +for (int i = 0; i < len; i++) { |
| 48 | + print(nums[i]); |
| 49 | +}``` |
| 50 | + |
| 51 | + |
| 52 | +#### Solution |
| 53 | + |
| 54 | +Language: **Java** |
| 55 | + |
| 56 | +```java |
| 57 | +class Solution { |
| 58 | + public int removeElement(int[] nums, int val) { |
| 59 | + int seat = 0; |
| 60 | + for (int i = 0; i < nums.length; i++) { |
| 61 | + if (nums[i] != val) { |
| 62 | + nums[seat++] = nums[i]; |
| 63 | + } |
| 64 | + } |
| 65 | + return seat; |
| 66 | + } |
| 67 | +} |
| 68 | +``` |
| 69 | + |
0 commit comments