2012-04-03 161 views
19

我想在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; ? 

有没有更好的更有效的方法,而无需使用临时数组也许这样做呢? 最后,假设数组中没有空值,所以一切都可以工作。 谢谢

编辑:不,这不是功课。

+2

这功课吗?如果是的话,请标记为这样。 – 2012-04-03 14:35:02

+2

考虑交换第一个和最后一个项目,然后是第二个和第二个项目,直到达到列表的一半。你只需要一个临时变量,并且仍然会在列表中一次? – 2012-04-03 14:36:01

+2

http://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java – 2012-04-03 14:36:02

回答

53

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

+4

+1事实上,由于OP现在说这不是作业,所以这是一个很好的答案。 – 2012-04-03 14:42:04

+0

喜欢解决方案。刚刚确认不需要临时阵列,请参阅:http://ideone.com/api/embed.js/link/xLLTpl ...单击“克隆”,然后“运行” – eddyparkinson 2013-01-23 04:22:47

+0

至少在Java 1.6中不起作用: System.out.println(X [0] +“to”+ X [X.length - 1]); \t \t \t Collections.reverse(Arrays.asList(X)); System.out.println(X [0] +“to”+ X [X.length - 1]); 打印: 2272.6270739116至186.704625250768 2272.6270739116至186.704625250768 – 2014-08-13 20:51:48

10

使用单个临时元素。

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; 
    } 
3

你可以做到这一点,而不需要一个临时数组

  • 循环从开头(或结尾无所谓)到阵列
  • 交换元件与元件的中间(最后元素 - 指数)(所以0和size - 1,1和size - 2等)
  • 你会做这样的事情来交换:
 
    temp = a[i]; 
    a[i] = a[end-i]; 
    a[end-i] = temp; 
  • 重复
12

您不需要使用临时数组;只需从开始到中途逐步穿过阵列,在i处交换元素array.length-i-1处的元素。要确保正确处理中间元素(并不难做到,但要确保。)

0

伪代码,假设0基于索引数组:

for i in range(0, len(array)/2): 
    swap(array[i], array[(len(array)-1)-i]) 
+0

这看起来不像Java。 – ceving 2013-12-05 10:10:38

+2

因此'伪代码' – mcfinnigan 2013-12-05 14:01:04

1

这里有两种解决方案:

loop to N/2 
     swap each element at i with element at N - i 

另一种解决方案是(根据您的情况)假通过索引扭转数组:

GetValueAt(int i){return array[N - i];} 
0

让我们考虑数组是整型数组,然后我们还可以寻找这样

ARR的解决方案 - 阵列整数的

for(int i=0,int J<arr.length-1 ; i<j ; i++,j--) 
{ 
    temp =a[i]; 
    a[i]=a[j]; 
    a[j]=temp; 
} 
-2

你可以在短短两个步骤执行此

ArrayList<Element> YourTempElement= new ArrayList<Element>(mElements); 
Collections.reverse(YourTempElement); 
+0

使用与接受的答案相同的方法,只是不那么优雅而且没有解释。 – 2017-06-21 04:10:12

+0

有没有需要解释兄弟俩的小小的两步nd我不解释。 – Darshan 2017-06-21 04:34:14

+0

堆栈溢出很好的解决方案解释事情。接受的答案是。如果已经有一个很好的答案说明你会这样做,或者如果根本没有办法写出一个好的答案,那么添加问题的答案就没有真正的意义了:这只会增加噪音。 – 2017-06-21 05:38:38