zoukankan      html  css  js  c++  java
  • 移动零元素--leetcode题解总结

    题目:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
    连接:

    解法一:

     var moveZeroes = function(nums) {
         let noZero = 0;
          for (let i = 0; i < nums.length; ++ i) {
              if (nums[i] !== 0) {
                  nums[noZero ] = nums[i];
    
                  if (noZero !== i) {
                      nums[i] = 0;
                  }
                  noZero ++;
              }
          }
      };
    

    解法二:

    • 双指针:快慢指针---慢指针用来填充非零元素,快指针用来遍历数组
    var moveZeroes = function (nums) {
          let slow = 0,fast = 0;
          while (fast < nums.length) {
              if (nums[fast] !== 0) {
                  nums[slow] = nums[fast];
                  slow ++;
              }
    
              fast ++;
          }
    			// 注意最后填充所有的零
          while (slow < nums.length) {
              nums[slow] = 0;
              slow ++;
          }
      }
    

    解法三(官方题解)

    思路及解法:

    • 使用双指针,左指针指向当前已经处理好的序列的尾部,右指针指向待处理序列的头部。
    • 右指针不断向右移动,每次右指针指向非零数,则将左右指针对应的数交换,同时左指针右移。
    • 注意到以下性质:
    • 左指针左边均为非零数;
    • 右指针左边直到左指针处均为零。
    • 因此每次交换,都是将左指针的零与右指针的非零数交换,且非零数的相对顺序并未改变。
    var moveZeroes = function (nums) {
        let left  = 0,right = 0;
        while (right < nums.length) {
            if (nums[right] !== 0) {
                  交换左右指针的元素
                  左指针指向当前已经处理好的序列尾部,右指针指向待处理的序列的头部
                  [nums[left],nums[right]]=[nums[right],nums[left]];
                let tmp = nums[left];
                nums[left] = nums[right];
                nums[right] = tmp;
                left ++;
            }
            right ++;
        }
    }
    

    解法四: (滚雪球)

    “雪球”由零组成的集合,每次都与雪球的最左边元素交换位置,
    每次遇到一个零,雪球增加一
    https://leetcode.com/problems/move-zeroes/discuss/172432/THE-EASIEST-but-UNUSUAL-snowball-JAVA-solution-BEATS-100-(O(n))-%2B-clear-explanation
    The idea is that we go through the array and gather all zeros on our road.
    Swap the most left 0 of our snowball with element.

     var moveZeroes = function(nums) {
         // 记录零的个数
        let snowBallSize = 0;
        for (let i = 0; i < nums.length; ++ i) {
            if (nums[i] === 0) {
                snowBallSize ++;
            } else if (snowBallSize > 0) {
                let tmp = nums[i];
                nums[i] = 0;
                nums[i - snowBallSize] = tmp;
            }
        }
    };
    
    慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!
  • 相关阅读:
    2020.10.23 19级training 补题报告
    2020.10.17 天梯赛练习 补题报告
    2020.10.16 19级training 补题报告
    2020.10.9 19级training 补题报告
    2020.10.10 天梯赛练习 补题报告
    2020.10.3 天梯赛练习 补题报告
    2020.10.2 19级training 补题报告
    第十届山东省ACM省赛复现补题报告
    VVDI Key Tool Plus Adds VW Passat 2015 Key via OBD
    Xhorse VVDI Prog Software V5.0.3 Adds Many MCUs
  • 原文地址:https://www.cnblogs.com/rookie123/p/14348912.html
Copyright © 2011-2022 走看看