0

I already know how to do this with an array length of 3, but I need help doing this with arrays of all lengths.

public int[] rotateLeft3(int[] nums) {
  int[] array = {nums[1], nums[2], nums[0]};
  return array;
}
HappyVirus
  • 23
  • 1
  • 6
  • Please see this http://stackoverflow.com/questions/7970857/java-shifting-elements-in-an-array and http://stackoverflow.com/questions/31834786/move-elements-n-steps-to-the-left-challenge – Sanchit Khera Jan 23 '17 at 03:34
  • 5
    Possible duplicate of [Java, Shifting Elements in an Array](http://stackoverflow.com/questions/7970857/java-shifting-elements-in-an-array) – CozyAzure Jan 23 '17 at 03:34
  • Do you know how to write a loop? You'll need one. – ajb Jan 23 '17 at 03:37

2 Answers2

0

Think of this like reversing an array to a certain point.

Say we have an array of [5,1,2,3,8,9] and you want to rotate it to the left kth times(in this case, let k be 2). So the resulting array would be [2,3,8,9,5,1]. Say let's attempt this by starting with reversing the whole array, so

public static void reverse(int startIndex, int stopIndex, int[] array){
        while(startIndex < stopIndex){
            int temp = array[startIndex];
            array[startIndex++] = array[stopIndex];
            array[stopIndex--] = temp;
        }
}

public static int[] rotate(int[] array, int k){
    reverse(0, array.length - 1, array);
    reverse(0, array.length - 1 - k, array);
    reverse(array.length - k, array.length - 1, array);
    return array;
}
  1. reversing the whole array, we should get [9,8,3,2,1,5]
  2. Now we see the subarrays are at its respective spot so we just need to reverse it so reverse [9,8,3,2] to [2,3,8,9] and reverse [1,5] to [5,1]
Bao Thai
  • 533
  • 1
  • 6
  • 25
0

This is circular left shift by 1 element .You can consider k value as 1 here.

 public class ArrayCircularShift {

    public static void main(String[] args) {
        int origArray[] = {3,2,1,4,5,6};

        // right shift by k
        int k = 3;
        int size = origArray.length;
        k = k % size;
        int rightShiftedArray[] = new int[size];

        //right shift 
        for(int i =0 ;i < size ; i++)
        {
              rightShiftedArray[(k + i ) % size ] = origArray[i];
        }

        System.out.println("right shifted array");
        for(int ele : rightShiftedArray)
            System.out.println(ele);

        //left shift by k
        int[] leftShiftedArray = new int[size];

        for(int i=0; i < size ; i++)
        {
             int pos = i - k;
             if(pos >= 0)
                leftShiftedArray[pos] = origArray[i];
             else
                leftShiftedArray[pos + size] = origArray[i];
        }

        System.out.println("left shifted array");
        for(int ele : leftShiftedArray)
            System.out.println(ele);
    }
}
Bhagwati Malav
  • 3,349
  • 2
  • 20
  • 33