當前位置:首頁 » 編程語言 » 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;
}

熱點內容
新建文件夾3在線 發布:2025-07-02 14:42:51 瀏覽:213
安卓手機微信默認瀏覽器怎麼設置 發布:2025-07-02 14:14:55 瀏覽:503
資料庫質檢 發布:2025-07-02 14:13:41 瀏覽:458
opensslvc編譯 發布:2025-07-02 14:13:31 瀏覽:885
linux三系統 發布:2025-07-02 14:13:30 瀏覽:39
華為雲穩定伺服器 發布:2025-07-02 13:58:09 瀏覽:428
安卓游戲在哪裡下載免費 發布:2025-07-02 13:58:08 瀏覽:597
mts壓縮 發布:2025-07-02 13:53:31 瀏覽:965
資料庫的事務事務 發布:2025-07-02 13:51:15 瀏覽:610
買五菱s3哪個配置好 發布:2025-07-02 13:51:11 瀏覽:773