反转数组顺序

新手上路,请多包涵

我正在尝试反转 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; ?

在不使用临时数组的情况下,是否有更好更有效的方法来做到这一点?最后,假设数组中没有空值,所以一切正常。谢谢

编辑:不,这不是作业。

原文由 marcwho 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 521
2 个回答

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

原文由 Louis Wasserman 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用单个临时元素。

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

原文由 ArjunShankar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏