Leetcode - Move Zeroes

Question

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].


Note

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Java Code

public void moveZeroes(int[] nums) {
    int len = nums.length;
    int i = 0;

    //遍歷數組前面連續的非零元素
    while(nums[i] != 0)
        if((++i) == len) return;

    //指針j用於依次遍歷數組的元素,指針i指向需要被覆蓋的元素
    //即把所有非零元素全部移動到數組前部,且按照原來的順序緊挨在一起
    int j = i;
    while(j < len) {
        if(nums[j] != 0)
            nums[i++] = nums[j];
        ++j;
    }

    //先得到數組中0的個數,再把數組後部置零,相當於把所有0後移
    int zeros = j - i;
    while(zeros > 0) {
        nums[len - zeros] = 0;
        --zeros;
    }   
}

發佈了74 篇原創文章 · 獲贊 24 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章