移動數組元素的位置

來源:互聯網
上載者:User

標籤:public   oid   exti   system.in   poi   move   改變   長度   整數   

題目:有 n 個整數,使其前面各數順序向後移 m 個位置,最後 m 個數變成最前面的 m 個數

原數組:
[2, 3, 4, 6, 7, 9]
請輸入要移動的位元:3
[6, 7, 9, 2, 3, 4]

數組的長度是有限的,移動超出數組長度的元素重新排在數組的前面

方法一,記錄移動的位置

比如整體向後移動兩位,也就是7,9的索引要變成0,1; 而2,3,4,6 的索引要加2;數組的長度len=6,利用這個關係,我們寫一個方法

    public static void function() {        int[] array={2,3,4,6,7,9};        //複製一個數組,用於資料的存放        int [] arraycopy=Arrays.copyOf(array, array.length);        //定義移動的位元        //索引        int len=array.length;        System.out.println("原數組:");        System.out.println(Arrays.toString(array));                System.out.println("請輸入要移動的位元:");        Scanner sc=new Scanner(System.in);        int moveNum=sc.nextInt();                int point=len-moveNum;//6-2=4        for (int i = 0; i < array.length; i++) {            if (i<point) {                arraycopy[i+moveNum]=array[i];//交換索引值            }            if (i>=point) {                arraycopy[i-point]=array[i];//交換索引值            }                    }        System.out.println("移動後:");        System.out.println(Arrays.toString(arraycopy));            }

方法2,可以利用數組的長度,用同樣的原理動態去改變數組各個元素索引的變化

 1 //動態變化索引  新的索引值=(原索引+移動位元)%數組長度,向右移動可以理解溢出,length是一個長度迴圈 2     public static void function01() { 3         int[] array={2,3,4,6,7,9}; 4         //複製一個數組,用於資料的存放 5         int [] arraycopy=Arrays.copyOf(array, array.length); 6         System.out.println("原數組:"); 7         System.out.println(Arrays.toString(array)); 8         System.out.println("請輸入要移動的位元:"); 9         Scanner sc=new Scanner(System.in);10         11         int moveNum=sc.nextInt();//移動的位元12         13         for (int i = 0; i < arraycopy.length; i++) {14             int move=(i+moveNum)%array.length;15             arraycopy[move]=array[i];16         }17         System.out.println(Arrays.toString(arraycopy));18         19         20     }

 

移動數組元素的位置

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.