【问题标题】:Move Zeros logic break down Javascript移动零逻辑分解Javascript
【发布时间】:2021-12-27 17:58:58
【问题描述】:

我正在研究我在 leetcode 的讨论部分中看到的这个解决方案,但我无法掌握部分逻辑。游戏的名称是将所有零移动到给定数组的末尾,同时保持其他数字的顺序。 j 索引内的增量运算符是我迷路的地方,因为那不是将非零数放在右边吗?

var moveZeroes = function(nums) {
    let j = 0
    for(let i = 0; i < nums.length; i++) {
       if(nums[i] !== 0) {
           //storing the index we are iterating on
           let n = nums[i]
           //changing the index in place to 0
           nums[i] = 0
           //console.log(nums);
           // 
           nums[j++] = n
           console.log(nums);
       }
   }
   return nums;
};

console.log(moveZeroes([0,1,0,3,12]));

【问题讨论】:

标签: javascript arrays algorithm data-structures


【解决方案1】:

记住 j++ 是后自增的,所以 j 的初始值是用来索引 nums 的,然后 j 是自增的。如果是 ++j,那么 j 会先递增,然后再使用。

【讨论】:

  • 这很有帮助!
【解决方案2】:

只需删除所有零。将删除的零添加到末尾。

var moveZeroes = (nums) =>
  (
    nums.toString().replaceAll("0,", "") +
    ",0".repeat(("" + nums).replace(/[^0]/g, "").length)
  )
    .split(",")
    .map(Number);
console.log(moveZeroes([0, 1, 0, 0, 3, 0, 12])); //[ 1, 3, 12, 0, 0, 0, 0 ]

注意:

  • (""+nums).replace(/[^0]/g,'').length: 数组中 0 的个数
  • nums.toString():要将数组转换为我们使用的字符串,或者我们可以使用与空字符串连接的技巧,例如""+nums
  • split(','): 将字符串转为数组
  • map(Number):将字符串数组转换为数字。

【讨论】:

    【解决方案3】:

    更新

    OP 想要改变数组,"Solution A" 处理不可变数组,"Sulution B" 改变数组。

    解决方案 A(不可变)

    尝试使用Array.filter() 将零(例如num === 0)和非零数字(例如num !== 0)分隔成两个新的独立数组。然后使用Array.concat()spread operator 将它们合并到一个数组中。

    // log() is an optional utility function that formats console logs
    const log = data => console.log(`[${data}]`);
    
    // This input array has zeroes everywhere
    const numbers = [0, 1, 0, 0, 3, 0, 12];
    
    const moveZeroes = array => {
      // With the given array called "numbers"
      // left = [1, 3, 13]
      const left = array.filter(num => num !== 0);
      // right = [0, 0, 0, 0]  
      const right = array.filter(num => num === 0);
      // Then arrays "left" and "right" are merged
      return [].concat(left, right)
    };
    
    log(moveZeroes(numbers));

    解决方案 B(可变)

    Array.reverse() 数组,使用Array.entries() 跟踪索引,并通过for...of loop 运行它。如果一个数字不是零,Array.splice() 将其输出,然后将 Array.unshift() 它放到数组的开头。请注意,.reverse().splice().unshift()mutating Array methods

    // log() is an optional utility function that formats console logs
    const log = data => console.log(`[${data}]`);
    
    // This input array has zeroes everywhere
    const numbers = [0, 1, 0, 0, 3, 0, 12];
    
    const moveZeroes = array => {
      /* .reverse() the array, track index with
      .entries(), and loop thru with a for...of
      loop */
      for (let [idx, num] of array.reverse().entries()) {
        /* if a number isn't zero, remove it with 
        .splice(), then .unshift() it into the
        beginning of array */
        if (num !== 0) {
          array.splice(idx, 1);
          array.unshift(num);
        }
      }
      return array;
    };
    
    log(moveZeroes(numbers));

    【讨论】:

    • 部分原因是不使用另一个数组并就地执行!
    • @Jaimie 查看更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 2015-01-16
    相关资源
    最近更新 更多