Given an array and a value, 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 in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
var id = nums.indexOf(val);
while(id !== -1){
nums.splice(id,1);
id = nums.indexOf(val);
}
return nums.length;
};
突然意识到,好像并不是让我用indexOf的,然后就写了第二种解法。
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
var j=0;
var ll = nums.length;
for(var i=0;i<ll;i++){
if(nums[i]!==val){
nums[j]=nums[i];
j++;
}
}
return j;
};
本文介绍了两种在JavaScript中从数组中移除指定值的方法。第一种使用`indexOf`和`splice`组合实现,第二种采用双指针技巧,只遍历一次数组即可完成元素过滤,提高效率。
419

被折叠的 条评论
为什么被折叠?



