正数、负数和零的挪动问题

把0挪放到最后

public class Test3 {
    public static void appendZero(int[] arr) {
        int left = 0;
        int right = arr.length-1;

        while (left <= right) {
            //从右边走起看右边 如果不是0 那么去右边找个0 来换,如果是0  就往左边移动
            while (right>=0 && arr[right] ==0){
                right--;
            }
            if (arr[right]!=0){
                while (left < right && arr[left] !=0){
                    left++;
                }
                swap(left, right, arr);
            }
            right--;
        }
    }
    public static void swap(int left, int right, int[] arr) {
        int temp = arr[left];
        arr[left]=arr[right];
        arr[right]=temp;
    }
    public static void main(String[] args) {

        int[] arr = {1,2,0,3,0,5,-1,4,-5};
        appendZero(arr);
       for (int result : arr){
           System.out.print(result+" ");
       }
    }

}

这样的结果是不能保证非0的数组元素顺序的:

 所以可以用空间换时间的方法做:

public class Test3 {
    public static void appendZero(int[] arr) {
        int right = arr.length - 1;
        int indexResultArr = 0;
        int[] resultArr  =new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i]==0) {
                resultArr[right]=0;
                right--;
            }else if (arr[i] !=0){
                resultArr[indexResultArr]=arr[i];
                indexResultArr++;
            }
        }

        for(int i=0; i<arr.length; i++) {
            arr[i]=resultArr[i];
        }

    }

    public static void main(String[] args) {

        int[] arr = { 1, 2, 0, 3, 0, 5, -1, 4, -5 };
        appendZero(arr);
        for (int result : arr) {
            System.out.print(result + " ");
        }
    }

}

这样是比较简单的

猜你喜欢

转载自www.cnblogs.com/toov5/p/10416187.html