反向数组顺序
我试图颠倒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; ?
有没有更好的方法可以在不使用临时数组的情况下执行此操作? 最后,假设数组中没有空值,所以一切都可以工作。 谢谢
编辑:不,这不是功课。
如果它是一个Object数组,那么Collections.reverse(Arrays.asList(array))
将以恒定的内存和线性时间完成这项工作 – 不需要临时数组。
您不需要使用临时数组; 从头到尾逐步遍历数组,在i
处交换元素,在array.length-i-1
处元素。 确保正确处理中间元素(不难做,但要确保。)
使用单个临时元素。
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; }
你可以在不需要临时数组的情况下完成它
- 从一开始(或结束无关紧要)循环到数组的中间
- 交换元素与元素at(最后一个元素 – 索引)(所以0和
size - 1
1,1和size - 2
等) - 你会做这样的事情来交换:
temp = a [i]; a [i] = a [end-i]; a [end-i] = temp;
- 重复
这是两个解决方案:
loop to N/2 swap each element at i with element at N - i
另一个解决方案是(根据您的具体情况)通过索引来反转数组:
GetValueAt(int i){return array[N - i];}
伪代码,假设基于0的索引数组:
for i in range(0, len(array)/2): swap(array[i], array[(len(array)-1)-i])
让我们考虑数组是Integer数组,然后我们也可以寻找这样的解决方案
arr – 整数数组
for(int i=0,int J
您只需两步即可完成此操作
ArrayList YourTempElement= new ArrayList (mElements); Collections.reverse(YourTempElement);