283. Move Zeroes(把数组中的 0 移到末尾)

iven 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.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

方法一:新开辟一个数组存储,比较简单,不列了。
方法二:移位(记录0的个数)
class Solution {
    public static void moveZeroes(int[] nums) {
        int n=nums.length;
        int [] order=new int[n];int count=0;
        for(int i=0;i<n;i++){
            if(nums[i]==0){
                count++; 
            }
            if(nums[i]!=0&&count!=0){
                nums[i-count]=nums[i];
                nums[i]=0;
            }
        }

    }
}

方法三:移位(记录新数组的个数)

class Solution {
    public static void moveZeroes(int[] nums) {
        int n=nums.length;
        int [] order=new int[n];
        int index=0;
        for(int i=0;i<n;i++){
            if(nums[i]!=0){
                nums[index++]=nums[i];
            }
        }
        for(int i=index;i<n;i++){
            nums[index++]=0;
        }

    }

 

posted on 2019-05-14 21:01  shaer  阅读(190)  评论(0编辑  收藏  举报

导航