PHZ*_*IDE 44 java arrays reverse
如果我有这样的数组:
1 4 9 16 9 7 4 9 11
Run Code Online (Sandbox Code Playgroud)
反转数组的最佳方法是什么,使它看起来像这样:
11 9 4 7 9 16 9 4 1
Run Code Online (Sandbox Code Playgroud)
我有下面的代码,但我觉得这有点单调乏味:
public int[] reverse3(int[] nums) {
return new int[] { nums[8], nums[7], nums[6], nums[5], num[4],
nums[3], nums[2], nums[1], nums[0] };
}
Run Code Online (Sandbox Code Playgroud)
有更简单的方法吗?
Vik*_*dor 70
Collections.reverse()
如果你把你的数字放在一个List
中,你可以为你做这个工作Integers
.
List<Integer> list = Arrays.asList(1, 4, 9, 16, 9, 7, 4, 9, 11);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 4, 9, 16, 9, 7, 4, 9, 11]
[11, 9, 4, 7, 9, 16, 9, 4, 1]
Run Code Online (Sandbox Code Playgroud)
Jor*_*son 65
如果要在适当位置反转数组:
Collections.reverse(Arrays.asList(array));
Run Code Online (Sandbox Code Playgroud)
它起作用,因为Arrays.asList返回原始数组的直写代理.
小智 32
如果您不想使用,Collections
那么您可以这样做:
for (i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
Run Code Online (Sandbox Code Playgroud)
Lui*_*ano 12
我喜欢保留原始数组并返回副本.这是一个通用版本:
public static <T> T[] reverse(T[] array) {
T[] copy = array.clone();
Collections.reverse(Arrays.asList(copy));
return copy;
}
Run Code Online (Sandbox Code Playgroud)
不保留原始数组:
public static <T> void reverse(T[] array) {
Collections.reverse(Arrays.asList(array));
}
Run Code Online (Sandbox Code Playgroud)
The*_*dak 11
试试这个:
public int[] reverse3(int[] nums) {
int[] reversed = new int[nums.length];
for (int i=0; i<nums.length; i++) {
reversed[i] = nums[nums.length - 1 - i];
}
return reversed;
}
Run Code Online (Sandbox Code Playgroud)
我的意见是:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
我得到的输出:
12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
归档时间: |
|
查看次数: |
186772 次 |
最近记录: |