用Java反转数组

编程入门 行业动态 更新时间:2024-10-22 19:44:25
本文介绍了用Java反转数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图以两种方式反转数组:

I am trying to reverse an array in 2 ways:

1)通过创建一个非常简单的新数组:

1) By creating a new array which was very easy:

public static int[] reverse(int[] array) { int[] reverseArray = new int[array.length]; for(int i = 0; i < reverseArray.length; i++) { reverseArray[i] = array[array.length - i - 1]; } return reverseArray; }

2)第二种方法我得到了答案,但实际上我不明白它非常好,它实际上使用交换,将数组的值赋予临时变量然后更改它并将其返回到原始变量:

2) The second method I got my answer but I actually don't understand it very well, it actually makes use of swapping, giving the value of the array to a temporary variable then changes it and returns it to the original variable:

public static int[] reverse2(int[] array) { for (int i=0; i < array.length / 2; i++) { int temp = array[i]; array[i] = array[array.length - i - 1]; array[array.length - i - 1] = temp; } return array; }

有人可以向我解释第二个代码吗? 我不明白2除法? 如果数组大小是偶数还是奇数会怎么样?

Could someone explain to me the second code? I don't understand the division by 2? What happens if the array size is even or odd?

推荐答案

除以2只是为了让你只去通过数组的前半部分。如果你交换第一个和最后一个项目,当我到达array.length时你不想再这样做。如果尺寸是均匀的,它将在下半部分之前停止,如果尺寸为奇数,它将在中心位置之前停止,无论如何都不需要切换。希望有所帮助!

The division by 2 is merely so you only go through the first half of the array. If you swap the first and last items, you don't want to do it again when i reaches array.length. If the size is even, it will stop before the second half, if the size is odd, it will stop before the center position, which doesn't need to be switched anyway. Hope that helps!

更多推荐

用Java反转数组

本文发布于:2023-06-04 08:34:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/493336.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!