leetcode-Easy-第8期-陣列型別-Remove Element
題目:在不建立新的陣列下,移除陣列中所有給定的值
Given an arraynums and a valueval , remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input arrayin-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
- Example
Given nums = [3,2,2,3], val = 3 移除目標值3陣列變成:[2,2] 所以返回長度為2
- 解法一
var removeElement = function(nums, val) { const len = nums.length for(let i = 0; i < len; i++){ if(nums[i] !== val){ nums.push(nums[i]) } } nums.splice(0,len) return nums.length };
- 解法二
const len = nums.length for(let i = 0; i < len; i++){ if(nums[i] !== val){ nums.splice(i,1) } } return nums.length