當前位置:首頁 » 編程語言 » java數組倒置

java數組倒置

發布時間: 2023-06-13 02:18:17

① Java 數組倒序輸出

1、逆序數組有很多種方法,比如先排序,再逆序存

public static void main(String[] args) {
int[] nums = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
System.out.print("原數組:");
for (int num : nums) {
System.out.print(num+" ");
}
System.out.print(" 倒序新數組:");
for (int num : reverseArray1(nums)) {
System.out.print(num + " ");
}
}

//1.排序後倒序
public static int[] reverseArray1(int[] nums) {
Arrays.sort(nums);
int[] reNums = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
reNums[i] = nums[nums.length - 1 - i];
}
return reNums;
}



//2.Collection 內置的逆序
public static int[] reverseArray2(int[] nums) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
list.add(nums[i]);
}
Collections.reverse(list);
int [] reNums = new int[nums.length];
for (int i = 0; i <nums.length ; i++) {
reNums[i] = list.get(i);
}
return reNums;
}

熱點內容
神秘顧客訪問 發布:2025-05-15 20:33:39 瀏覽:296
安卓市場手機版從哪裡下載 發布:2025-05-15 20:17:28 瀏覽:814
幼兒速演算法 發布:2025-05-15 20:15:08 瀏覽:86
best把槍密碼多少 發布:2025-05-15 20:13:42 瀏覽:548
android安裝程序 發布:2025-05-15 20:13:20 瀏覽:559
c語言跳出死循環 發布:2025-05-15 20:06:04 瀏覽:824
a19處理器相當於安卓哪個水平 發布:2025-05-15 20:05:29 瀏覽:639
榮耀9i安卓強行關機按哪個鍵 發布:2025-05-15 20:00:32 瀏覽:750
密碼鎖寫什麼最好 發布:2025-05-15 19:05:31 瀏覽:783
5的源碼是 發布:2025-05-15 19:04:07 瀏覽:719