leetcode之數組反轉

public class Pan {
    public static void main(String[] args) {
        int[] a = new int[5];
        a[0] = (int) (Math.random() * 100);//隨機生成1~100的浮點數,然後強轉成int
        a[1] = (int) (Math.random() * 100);
        a[2] = (int) (Math.random() * 100);
        a[3] = (int) (Math.random() * 100);
        a[4] = (int) (Math.random() * 100);
 
        System.out.println("數組中各個值是:");
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
         
        /*思路一: 使用臨時數組*/
         
        System.out.println();
        //準備臨時數組
        int[] temp = new int[a.length];
        //把原數組的內容複製給臨時數組
        for (int i = 0; i < temp.length; i++) {
            temp[i] = a[i];
        }
        System.out.println("臨時數組中的各個值是:");
        for (int i = 0; i < temp.length; i++)
            System.out.print(temp[i] + " ");
        System.out.println();
        //反轉的做法是把臨時數組的數據,挨個 倒 放入 原數組中
        for (int i = 0; i < temp.length; i++) {
            a[i] = temp[temp.length-1-i];
        }
  
        System.out.println("反轉後的數組中各個值是:");
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
         
        System.out.println();
         
        /*思路二: 進行首尾調換*/      
        for (int i = 0; i < a.length/2; i++) {
            int middle = a[a.length-i-1];
            a[a.length-i-1] = a[i];
            a[i] = middle;
        }       
        System.out.println("再次反轉後的數組中各個值是:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
         
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章