Reverse Array Order

前端 未结 8 1137
独厮守ぢ
独厮守ぢ 2020-12-01 15:50

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 co

8条回答
  •  独厮守ぢ
    2020-12-01 16:39

    you can do it without needing a temp array

    • loop from the beginning (or end doesn't matter) to the middle of the array
    • swap element with element at (last element - index) (so 0 and size - 1, 1 and size - 2 etc)
    • you'll do something like this to swap:
        temp = a[i];
        a[i] = a[end-i];
        a[end-i] = temp;
    
    • repeat

提交回复
热议问题