算法:移动数组中的零

1.问题描述

问题描述:
    给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序
示例:
    输入:[0,1,0,3,12]
    输出:[1,3,12,0,0]
说明:
    1.必须在原数组上操作,不得拷贝额外的数组
    2.尽量减少操作次数

2.解法

public class Main {
    public static void main(String[] args) {

    }
    public void moveZerosone(int nums[]){
        //如果数组为空或者长度为0,则直接返回
        if(nums==null||nums.length==0){
            return;
        }
        //设置参数index
        int index=0;
        //通过循环将非零值依次存到原数组,然后其余值直接赋值为0
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=0){
                //存储值,index自增先赋值后改变
                nums[index++]=nums[i];
            }
        }
        while(index<nums.length){
            nums[index++]=0;
        }
    }
    //采用递归的思想
    public void moveZerostwo(int nums[]){
        int i=0;
        //统计前面0的个数
        for(int j=0;j<nums.length;j++){
            if(nums[j]==0){
                i++;
                //如果当前数为0就不操作
            }else if(i!=0){
                //否则,把当前数字放到最前面0的位置,然后再把当前位置设为0
                nums[j-i]=nums[j];
                nums[j]=0;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/dongxuelove/p/14026145.html