xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode 283. Move Zeroes All In One

LeetCode 283. Move Zeroes All In One

array in-place swap / 数组就地交换算法

errors


function moveZeroes(nums: number[]): void {
  // in-place 就地交换
  let index = 0;
  // let flag = false;
  for(let i = 0; i < nums.length; i++) {
    if(nums[i] === 0) {
      index = i;
      flag = true;
      console.log(`index =`, index);
    } else {
      // nums[index] !== 0
      console.log(`flag =`, flag);
      if(flag) {
        // swap
        [
          nums[index],
          nums[i]
        ] = [
          nums[i],
          nums[index]
        ];
        index = i;
        console.log(`nums =`, nums);
        // clear
        flag = false;
      }
    }
  }
};

solutions ✅

/**
 Do not return anything, modify nums in-place instead.
 */

function moveZeroes(nums: number[]): void {
  // in-place 就地交换
  for(let i = 0; i < nums.length - 1; i++) {
    let j = i + 1;
    while(nums[j] === 0 && j < nums.length - 1) {
      j += 1;
    }
    // console.log(`j`, j, nums[j])
    if(nums[i] === 0) {
      // swap
      [
        nums[j],
        nums[i]
      ] = [
        nums[i],
        nums[j]
      ];
    }
  }
};

demos


image

https://leetcode.com/problems/move-zeroes/description/?envType=study-plan-v2&envId=leetcode-75

https://leetcode.com/problems/move-zeroes/solutions/5204027/leetcode-283-move-zeroes-solution/

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://leetcode.com/studyplan/leetcode-75/



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2024-05-25 11:00  xgqfrms  阅读(3)  评论(0编辑  收藏  举报