Java - Rotating array

后端 未结 14 1073

So the goal is to rotate the elements in an array right a times. As an example; if a==2, then array = {0,1,2,3,4} would become

相关标签:
14条回答
  • 2020-11-27 20:03

    Arraycopy is an expensive operation, both time and memory wise. Following would be an efficient way to rotate array without using extra space (unlike the accepted answer where a new array is created of the same size).

    public void rotate(int[] nums, int k) { // k = 2
        k %= nums.length;
        // {0,1,2,3,4}
    
        reverse(nums, 0, nums.length - 1); // Reverse the whole Array
        // {4,3,2,1,0}
    
        reverse(nums, 0, k - 1); // Reverse first part (4,3 -> 3,4)
        // {3,4,2,1,0}
    
        reverse(nums, k, nums.length - 1); //Reverse second part (2,1,0 -> 0,1,2)
        // {3,4,0,1,2}
    }
    
    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 20:05

    Add a modulo array length to your code:

    // create a newArray before of the same size as array
    
    // copy
    for(int x = 0; x <= array.length-1; x++){
      newArray[(x+a) % array.length ] = array[x];
    }
    

    You should also create a new Array to copy to, so you do not overwrite values, that you'll need later on.

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