题目:在不创建新的数组下,移除数组中所有给定的值
Given an array nums and a value val, 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 array in-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