tailgo / poorguy-fly

1 stars 0 forks source link

27. 移除元素(简单)-https://leetcode-cn.com/problems/remove-element/submissions/ #9

Open zhaojianing opened 5 years ago

zhaojianing commented 5 years ago

执行用时 : 128 ms, 在Remove Element的JavaScript提交中击败了23.44% 的用户 内存消耗 : 34.1 MB, 在Remove Element的JavaScript提交中击败了6.97% 的用户

方法不太行,在考虑一下。

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    for (let i=0;i<nums.length;i++) {
        if (nums[i] === val) {
            nums.splice(i,1);
            i--;
        }
    }
    return nums.length;
};

第二种
执行用时 : 68 ms, 在Remove Element的JavaScript提交中击败了99.13% 的用户 内存消耗 : 33.7 MB, 在Remove Element的JavaScript提交中击败了35.08% 的用户

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    let len = nums.length;
    let i = 0;
    for (let j = 0; j < len; j++) {
        if (nums[j] !== val) {
            nums[i++] = nums[j];
        }
    }
    return i;
};

更偏向于结果

tailgo commented 5 years ago

执行用时 : 68 ms, 在Remove Element的JavaScript提交中击败了99.13% 的用户 内存消耗 : 33.4 MB, 在Remove Element的JavaScript提交中击败了96.24% 的用户

题目要求原地操作数组,所以就选择把命中的数用数组末尾的数来代替。

var removeElement = function(nums, val) {
    var l = nums.length
    for (var i = 0; i < l; ++i) {
        if (nums[i] == val) {
            while (nums[l - 1] == val && i < l - 1) {
                l--;
            }
            nums[i] = nums[l - 1];
            l--;
        }
    }
    if (l < 0) return 0;
    return l;
};