Java – using less memory requires reordering array elements

I have a recent interview question about reordering elements in an array with minimum memory usage Do not use any other variables or sets, etc

Input:

value   65 7 1 68 90
index    0 1 2  3  4

Output:

value   90 68 1 7 65
index    0  1 2 3  4

Solution

You can use XOR to swap between elements (the first is the last, the second is from the end, and so on), as follows:

int [] arr = {65,7,1,68,90};
for(int i=0; i<arr.length/2; i++){
    // the following 3 lines swap between elements arr[i] and arr[arr.length-i-1]
    arr[i] = arr[i] ^ arr[arr.length-i-1];
    arr[arr.length-i-1] = arr[i] ^ arr[arr.length-i-1];
    arr[i] = arr[i] ^ arr[arr.length-i-1];
}

for(int i=0; i<arr.length; i++){
    System.out.print(arr[i]+" ");
}

OUTPUT

90 68 1 7 65
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>