反转数组顺序 [英] Reverse Array Order
问题描述
我试图在 java 中颠倒数组的顺序.
在 O(n) 中以最少的内存使用最有效的方法是什么.
不需要用代码回答,伪代码就可以了.
这是我的思考过程:
I am trying to reverse the order of an Array in java.
What is the most efficient way to do so in O(n) with the least amount of memory used.
No need to answer with code, pseudo code will be fine.
Here is my thought process:
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; ?
有没有更好更有效的方法来做到这一点,也许不使用临时数组?最后,假设数组中没有空值,所以一切正常.谢谢
Is there a better more efficient way to do this perhaps without using a temp array? and Lastly, assume that there are no nulls in the array, so everything can work. Thank you
不,这不是作业.
推荐答案
如果它是一个 Object 数组,那么 Collections.reverse(Arrays.asList(array))
将使用常量内存来完成这项工作,并且线性时间——不需要临时数组.
If it's an Object array, then Collections.reverse(Arrays.asList(array))
will do the job with constant memory and linear time -- no temporary array required.
这篇关于反转数组顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!