Move Zeroes:数组重排列

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

思路:两个下标扫描数组,n扫描非零,z扫描0元素,用非0元素向前移动,最后,剩余位置补0。

为了移动次数最少,被替换元素不变的地方就直接跳过。

class Solution {
    public void moveZeroes(int[] nums) {
        int n = 0,z = 0;//z表示0的位置,n表示非0位置
        if(nums.length ==0 ) return;
        while(nums[z]!=0) {//将z初始化到第一个0元素的位置
          z++;
          if(z>=nums.length) return;
        }
        n = z +1;
        //System.out.println(z+","+n);
        while(n<nums.length){
            if(nums[n] != 0){
                if(nums[n] != nums[z]){
                    nums[z] = nums[n];                   
                }
                z++;
            }
            n++;
        }
        while(z<nums.length){
            if(nums[z]!=0){
             nums[z] = 0;   
            }
            z++;
        }
    }
}







版权声明:本文为u013300579原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。