我正在尝试反转 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 许可协议
如果它是一个对象数组,那么
Collections.reverse(Arrays.asList(array))
将以恒定的内存和线性时间完成这项工作——不需要临时数组。