【Java】【JS】LeetCode - 雙指針 - #283 移動零

我未必光芒萬丈,但始終溫暖有光。樂扣樂扣:https://leetcode-cn.com/problems/move-zeroes/

#283 移動零

給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾,同時保持非零元素的相對順序。

說明:

  1. 必須在原數組上操作,不能拷貝額外的數組。
  2. 儘量減少操作次數。
輸入: [0,1,0,3,12]

輸出: [1,3,12,0,0]

算法圖畫講解參考:https://leetcode-cn.com/problems/move-zeroes/solution/dong-hua-yan-shi-283yi-dong-ling-by-wang_ni_ma/ 

方法一:覆蓋

非0項直接覆蓋到數組前頭
遍歷數組,將非0項覆蓋到數組中,從頭開始覆蓋
所有非0項被安排到數組的前頭,然後將剩下的項覆蓋爲0

class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null){
            return;
        }
        int j = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] != 0){   // 不爲零就覆蓋之前指針項
                nums[j] = nums[i];
                j++;
            }
        }
        for(int i = j;i < nums.length; i++){ // 不全剩下位數
            nums[i] = 0;
        }
    }
}

方法二:交換

i 、 j 指針初始都指向索引 0
i 指針負責掃描整個數組,遇到了非0項,就與 j 指向的項交換,不管它是否爲 0
因此非 0 項被不斷交換到數組的前部, 0 都跑到數組的最右

class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null){
            return;
        }
        int j = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i]!=0){
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                j++;
            }
        }
    }
}

JS 寫法類似,在此不再給出代碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章