zoukankan      html  css  js  c++  java
  • 正数、负数和零的挪动问题

    把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 + " ");
            }
        }
    
    }

    这样是比较简单的

  • 相关阅读:
    Java中抽象类和接口的区别(abstract class VS interface)
    ECUST_Algorithm_2019_4
    ECUST_Algorithm_2019_3
    杂题
    ECUST_Algorithm_2019_2
    Magolor的数据结构作业
    ECUST_Algorithm_2019_1
    atcoder 泛做
    2018中国大学生程序设计竞赛
    UVA
  • 原文地址:https://www.cnblogs.com/toov5/p/10416187.html
Copyright © 2011-2022 走看看