circular left shift of an array by n positions in java

前端 未结 12 2354
醉梦人生
醉梦人生 2020-12-31 20:16

I am trying to do the circular left shift of an array by n positions using only a single 1D array. I can do it in two arrays, but I haven\'t figured out how to do it using o

12条回答
  •  不思量自难忘°
    2020-12-31 21:09

    Here is the very easy algorithm, with O(1) Space in O(n)
    Algorithm

    • Reverse the array from 0 to n (numberOfPositions) positions
    • Reverse the array from n+1 to array length - 1 positions
    • Reverse the whole array from 0 to length - 1 positions


     public class ArrayRotator {
    
     private final int[] target;
     private final int length;
    
     public ArrayRotator(int[] seed) {
        this.target = seed;
        this.length = seed.length;
     }
    
     public void rotateInline(int numberOfPositions) {
        reverse(0, numberOfPositions);
        reverse(numberOfPositions + 1, length-1);       
        reverse(0, length-1);
     }
    
     private void reverse(int start, int end) {
        for (int i = start; i <= (start + end)/2; i++) {
            swap(i, start + end - i);
        }
     }
    
     private void swap(int first, int second) {
        int temp = this.target[second];
        this.target[second] = this.target[first];
        this.target[first] = temp;
     }
    }
    


    For example, lets say the array is [1,2,3,4] and n is 2
    After step one, you would end up [2,1,3,4]
    After Step two, you would end up [2,1,4,3]
    After Step three, you would end up [3,4,1,2]

提交回复
热议问题