发布网友 发布时间:2022-04-22 22:52
共1个回答
热心网友 时间:2023-06-27 01:44
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("\n倒序新数组:");
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;
}