數組中元素位置移動實現

來源:互聯網
上載者:User

標籤:實現   就是   操作   length   位置   改變   sys   數組   new   

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

分析:實現移動其實就是對索引進行操作,數組元素沒有改變,而索引值發生了改變,

合理運用%運算,原數組索引%len=原數組的索引——>(原數組索引+移動位元)%len=新數組索引

    public static void function01() {        int[] array={2,3,4,6,7,9};        //複製一個數組,用於資料的存放        int [] arraycopy=Arrays.copyOf(array, array.length);        System.out.println("原數組:");        System.out.println(Arrays.toString(array));        System.out.println("請輸入要移動的位元:");        Scanner sc=new Scanner(System.in);                int moveNum=sc.nextInt();//移動的位元                for (int i = 0; i < arraycopy.length; i++) {            int move=(i+moveNum)%array.length;            arraycopy[move]=array[i];        }        System.out.println(Arrays.toString(arraycopy));                    }

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

 

數組中元素位置移動實現

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.