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

    这样是比较简单的

  • 相关阅读:
    VC++ 之 文件操作
    Delphi7 API(5) 消息篇:WM_LBUTTONDOWN、WM_LBUTTONUP、WM_MOUSEMOVE
    VC++ 之 输入/输出类库(二)
    VB 访问控制面板
    Delphi7 API(4) 消息_重绘
    Lisp简明教程
    一次快速排序错误引发的思考(2)
    一次快速排序错误引发的思考(1)
    Common Lisp编译程序的小技巧
    暴风影音5免去广告的小技巧
  • 原文地址:https://www.cnblogs.com/toov5/p/10416187.html
Copyright © 2011-2022 走看看