283.移动零

题目

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

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

方法一

class Solution {
    public void moveZeroes(int[] nums) {
        int n=nums.length,count=0;
        //统计0的个数
        for (int i = 0; i < n; i++) {
            if(nums[i]==0) count++;
        }
        //使得前n-count个数都不为0
        for(int i=0;i<n-count;++i){
            //使用while保证最终的nums[i]不为0
            while(nums[i]==0){
                for(int j=i+1;j<n;++j){
                    nums[j-1]=nums[j];
                }
                nums[n-1]=0;
            }
        }
    }
}

方法二(推荐)

把一个数组当做两个数组来用,不用担心数值被覆盖,因为覆盖的数值已知为0。

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

方法三

public void moveZeroes(int[] nums) {
    for(int i=0,count=0;i<nums.length;i++){
        if(nums[i] != 0){
            //执行替换操作
            if(count != i){//如果count!=i,则nums[count]必定为0
                nums[count] = nums[i];
                nums[i] = 0;
            }
            count++;
        }
    }
}

原题链接:https://leetcode-cn.com/problems/move-zeroes

原文地址:https://www.cnblogs.com/Frank-Hong/p/14195354.html