用Java反转数组 [英] Reverse an array in Java

查看:158
本文介绍了用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反转数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆