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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章