反向数组顺序

mar*_*who 19 java arrays reverse

我试图扭转java中数组的顺序.
在O(n)中使用最少内存量的最有效方法是什么.
无需用代码回答,伪代码就行了.
这是我的思考过程:

  create a new temp array //I think this is a waste of memory, 
                          //but I am not sure if there's a better way
 grab elements from the end of the original array -decrement this variable
 insert element in beginning of temp array -increment this variable
then make the original array point to the temp array? //I am not sure 
            //if I can do this in java; so let's say the 
            //original array is Object[] arr; and the temp array is 
            //Object[] temp. Can I do temp = arr; ?
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法可以在不使用临时数组的情况下执行此操作?最后,假设数组中没有空值,所以一切都可以工作.谢谢

编辑:不,这不是功课.

Lou*_*man 53

如果它是一个Object数组,那么Collections.reverse(Arrays.asList(array))将使用恒定的内存和线性时间来完成工作 - 不需要临时数组.

  • +1确实,既然OP现在说这不是作业,这是一个很好的答案. (4认同)

Ern*_*ill 12

您不需要使用临时数组; 从头到尾逐步遍历数组,将元素交换i为元素at array.length-i-1.确保正确处理中间元素(不难做,但要确保.)


Arj*_*kar 11

使用单个临时元素.

int array[SIZE];
int temp;

for (int i = 0; i < SIZE/2; i++)
  {
     temp = array[i];
     array[i] = array[SIZE-1 - i];
     array[SIZE-1 - i] = temp;
  }
Run Code Online (Sandbox Code Playgroud)