java 二維數組行列互換

來源:互聯網
上載者:User

標籤:意圖   out   pre   次數   void   維數   eve   需求   java   

代碼需求:

對等行等列的二維數組進行 行列 的互換

分析過程
  • 主對角線是保持不變
  • 行列互換即角標互換:[0][1] => [1][0]
  • 迴圈次數:外層迴圈行,內層迴圈每一行的列

代碼實現
public class ArrayReverse {    public static void main(String[] args) {        int arry[][] = new int[][] {{1,2,3},{4,5,6},{7,8,9}};        reverse(arry);        printArray(arry);    }    /**     * 二維數組轉置     * @param arry     */    public static void reverse(int arry[][]) {        int count = 0;//用於統計總共迴圈次數        for(int i=0; i< arry.length-1; i++) {            //列迴圈從:i+1開始,提高迴圈效率            for(int j=i+1; j< arry[i].length; j++) {                int temp = arry[i][j];                arry[i][j] = arry[j][i];                arry[j][i] = temp;                count++;            }        }        System.out.println(count);    }        public static void printArray(int array[][]){        for(int i=0;i<array.length; i++) {            for(int j = 0; j< array[i].length; j++) {                System.out.print(array[i][j]+"、");            }            System.out.println();        }    }}
總結

內層迴圈(列迴圈)迴圈的起始點 = 外層迴圈+1;比從j=0迴圈節省了迴圈次數,提高效率。

如有更好的演算法,還望道友下發留言幫忙改進!

java 二維數組行列互換

聯繫我們

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