|
| 1 | +package array_and_string |
| 2 | + |
| 3 | +/** |
| 4 | + * 27. Remove Element |
| 5 | + * <p> |
| 6 | + * Given an array nums and a value val, remove all instances of that value in-place and return the new length. |
| 7 | + * <p> |
| 8 | + * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. |
| 9 | + * <p> |
| 10 | + * The order of elements can be changed. It doesn't matter what you leave beyond the new length. |
| 11 | + * <p> |
| 12 | + * Example 1: |
| 13 | + * <p> |
| 14 | + * Given nums = [3,2,2,3], val = 3, |
| 15 | + * <p> |
| 16 | + * Your function should return length = 2, with the first two elements of nums being 2. |
| 17 | + * <p> |
| 18 | + * It doesn't matter what you leave beyond the returned length. |
| 19 | + * <p> |
| 20 | + * Example 2: |
| 21 | + * <p> |
| 22 | + * Given nums = [0,1,2,2,3,0,4,2], val = 2, |
| 23 | + * <p> |
| 24 | + * Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. |
| 25 | + * <p> |
| 26 | + * Note that the order of those five elements can be arbitrary. |
| 27 | + * <p> |
| 28 | + * It doesn't matter what values are set beyond the returned length. |
| 29 | + * <p> |
| 30 | + * Clarification: |
| 31 | + * <p> |
| 32 | + * Confused why the returned value is an integer but your answer is an array? |
| 33 | + * <p> |
| 34 | + * 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. |
| 35 | + * <p> |
| 36 | + * Internally you can think of this: |
| 37 | + * <p> |
| 38 | + * // nums is passed in by reference. (i.e., without making a copy) |
| 39 | + * int len = removeElement(nums, val); |
| 40 | + * <p> |
| 41 | + * // any modification to nums in your function would be known by the caller. |
| 42 | + * // using the length returned by your function, it prints the first len elements. |
| 43 | + * for (int i = 0; i < len; i++) { |
| 44 | + * print(nums[i]); |
| 45 | + * } |
| 46 | + */ |
| 47 | + |
| 48 | +func removeElement(nums []int, val int) int { |
| 49 | + aimLength := 0 |
| 50 | + for _, n := range nums { |
| 51 | + if n != val { |
| 52 | + nums[aimLength] = n |
| 53 | + aimLength++ |
| 54 | + } |
| 55 | + } |
| 56 | + return aimLength |
| 57 | +} |
0 commit comments