Reverse Array Order

前端 未结 8 1101
独厮守ぢ
独厮守ぢ 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:33

    Lets consider the array is of array of Integer then we could also look for a solution like this

    arr - array of Integer

    for(int i=0,int J<arr.length-1 ; i<j ; i++,j--)
    {
        temp =a[i];
        a[i]=a[j];
        a[j]=temp;
     }
    
    0 讨论(0)
  • 2020-12-01 16:35

    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.

    0 讨论(0)
  • 2020-12-01 16:35

    You can Do this in just two steps

    ArrayList<Element> YourTempElement= new ArrayList<Element>(mElements);
    Collections.reverse(YourTempElement);
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-01 16:46

    Use a single temp element.

    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;
      }
    
    0 讨论(0)
  • 2020-12-01 16:53

    You don't need to use a temporary array; just step through the array from the beginning to half-way through, swapping the element at i for the element at array.length-i-1. Be sure the handle the middle element correctly (not hard to do, but do make sure.)

    0 讨论(0)
提交回复
热议问题