反转字符数组而不创建新数组
如何就地反转数组(无需创建新数组)?
How can I reverse an array in place (without creating a new array)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何就地反转数组(无需创建新数组)?
How can I reverse an array in place (without creating a new array)?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(13)
反转字符数组而不创建新数组
reversing an array of characters without creating a new array
不必费心在内存中反转数组,只需向后迭代即可!
Dont bother reversing the array in memory, just iterate over it backwards!
这是在不使用临时变量或其他数组的情况下反转数组元素的解决方案。这仅适用于 Java 8 及以上版本。
谢谢,
Here is the solution to reverse an array elements without using temp variable or another array. This will work only Java 8 and above version.
Thanks,
这是一个完整的程序,只需复制粘贴并在 IDE 中运行它:
输出:
Here is a complete program, just copy paste and run it in your IDE :
output :
static int[] reverseArray(int[] a) {
static int[] reverseArray(int[] a) {
家庭作业意味着仅由我提供的伪代码,通过不指定您想要的语言,您已经使伪代码变得相对容易:-)
将其转换为您选择的语言:
理想的做法是在您的头脑中实际运行该算法,使用一张纸来跟踪变量:
i1
和i2
。临时变量
。我倾向于为更简单的算法这样做。对于更难的任务,我会插入调试语句,以便计算机可以为我完成这项繁重的工作。因此,从一张纸开始:
然后逐个执行步骤,检查和/或更改每一列。这将使您比仅仅给出一些代码更好地理解它是如何工作的。
Homework means pseudo-code only from me, which you've made relatively easy by not specifying what language you want anyway :-)
Turn this into your language of choice:
An ideal thing to do is to actually run that algorithm in your head, using a piece of paper to keep track of variables:
i1
andi2
.temporary variable
.I tend to do that for simpler algorithms. Harder ones I insert debug statement into so that the computer can do that grunt work for me. Start with a piece of paper thus:
and just run through the steps one by one, checking and/or changing each column as you go. That will result in you understanding how it works far better than just being given some code.
使用 java 反转字符数组而不创建新数组。
如果你想反转int array,你必须将
public static void reviveArray(String[] array)
更改为public static void reviveArray(int[] array)
和String temp
作为int temp
。示例:
输出:
Reverse an array of characters without creating a new array using java.
If you want to reverse int array, you have to change
public static void reverseArray(String[] array)
aspublic static void reverseArray(int[] array)
andString temp
asint temp
.Example:
Output :
使用单个变量作为临时缓冲区,不断交换两端。在伪代码中:
等等。
Swap the ends constantly, using a single variable as a temporary buffer. In pseudo-code:
and so on.