美文网首页
27. Remove Element

27. Remove Element

作者: f1a94e9a1ea7 | 来源:发表于2018-11-25 21:25 被阅读7次

给一个数组和一个数值,去掉数组里面和这个数值一样的数组项,返回最后数组长度。

解析:

这道还是很简单的,就是循环一遍找到一样的值删掉就可以了,我是从前往后循环的,虽然答案是对的,但是速度慢。让数组从后往前循环会更快。

(The following English translation may not be right -.-)

analyze:

This question is so easy, just need a loop, and if you loop the array from the end to the start, the running speed will more fast.

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) { 

    for(var i = nums.length -1; i >= 0; i--){
        if(nums[i] === val){
            nums.splice(i,1);
        }
    }
};

相关文章

网友评论

      本文标题:27. Remove Element

      本文链接:https://www.haomeiwen.com/subject/ohymqqtx.html