|
| 1 | +# 027. Remove Element |
| 2 | + |
| 3 | +**<font color=red>难度: Easy</font>** |
| 4 | + |
| 5 | +## 刷题内容 |
| 6 | + |
| 7 | +> 原题连接 |
| 8 | +
|
| 9 | +* https://leetcode.com/problems/remove-element |
| 10 | + |
| 11 | +> 内容描述 |
| 12 | +
|
| 13 | +Given an array nums and a value val, remove all instances of that value in-place and return the new length. |
| 14 | + |
| 15 | +Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. |
| 16 | + |
| 17 | +The order of elements can be changed. It doesn't matter what you leave beyond the new length. |
| 18 | + |
| 19 | +#### Example 1: |
| 20 | + |
| 21 | + Given nums = [3,2,2,3], val = 3, |
| 22 | + |
| 23 | + Your function should return length = 2, with the first two elements of nums being 2. |
| 24 | + |
| 25 | + It doesn't matter what you leave beyond the returned length. |
| 26 | + |
| 27 | +#### Example 2: |
| 28 | + |
| 29 | + Given nums = [0,1,2,2,3,0,4,2], val = 2, |
| 30 | + |
| 31 | + Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. |
| 32 | + |
| 33 | + Note that the order of those five elements can be arbitrary. |
| 34 | + |
| 35 | + It doesn't matter what values are set beyond the returned length. |
| 36 | + |
| 37 | +#### Clarification: |
| 38 | + |
| 39 | +Confused why the returned value is an integer but your answer is an array? |
| 40 | + |
| 41 | +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. |
| 42 | + |
| 43 | +Internally you can think of this: |
| 44 | + |
| 45 | + // nums is passed in by reference. (i.e., without making a copy) |
| 46 | + int len = removeElement(nums, val); |
| 47 | + |
| 48 | + // any modification to nums in your function would be known by the caller. |
| 49 | + // using the length returned by your function, it prints the first len elements. |
| 50 | + for (int i = 0; i < len; i++) { |
| 51 | + print(nums[i]); |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | +## 解题方案 |
| 56 | + |
| 57 | +> 思路 1 |
| 58 | +******- 时间复杂度: O(N)******- 空间复杂度: O(1)****** |
| 59 | + |
| 60 | +保留两个指针 i 和 j,其中 i 是慢指针,j 是快指针。当 nums[j] 与给定的值相等时,递增 j 以跳过该元素。只要 nums[j] !== val,我们就复制 nums[j] 到 nums[i] 并同时递增两个索引。重复这一过程,直到 j 到达数组的末尾,该数组的新长度为 i。 |
| 61 | + |
| 62 | +代码: |
| 63 | + |
| 64 | +```javascript |
| 65 | +/** |
| 66 | + * @param {number[]} nums |
| 67 | + * @param {number} val |
| 68 | + * @return {number} |
| 69 | + */ |
| 70 | +var removeElement = function (nums,val) { |
| 71 | + let j = 0; |
| 72 | + for(let i = 0,len = nums.length; i<len; i++){ |
| 73 | + if(nums[i] !== val){ |
| 74 | + nums[j] = nums[i]; |
| 75 | + j++ |
| 76 | + } |
| 77 | + } |
| 78 | + return j; |
| 79 | +}; |
| 80 | +``` |
| 81 | + |
0 commit comments