Java > Array-1 > rotateLeft3 (CodingBat Solution)

Problem:

Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}.

rotateLeft3({1, 2, 3}) → {2, 3, 1}
rotateLeft3({5, 11, 9}) → {11, 9, 5}
rotateLeft3({7, 0, 0}) → {0, 0, 7}


Solution:

public int[] rotateLeft3(int[] nums) {
  
  return new int[] {nums[1],nums[2],nums[0]}; 
}


12 comments :

  1. package com.array1;

    public class RotateLeft {
    public static void main(String args[]){
    RotateLeft rotateLeftObject=new RotateLeft();
    for(int aryObject:rotateLeftObject.returnRotateArray(new int[]{1,2,3,4,5,6}))
    System.out.printf("%d ",aryObject);
    }
    public int[] returnRotateArray(int[] ary){
    int[] returnAry=new int[ary.length];
    int count=0;
    for(int i=1;i<ary.length;i++){
    returnAry[count]=ary[i];
    count++;
    }
    returnAry[ary.length-1]=ary[0];
    return returnAry;
    }



    }

    ReplyDelete
  2. hey, can you explain why did you put the nums in this order? why shouldn't it be return new int[] {nums[2], nums[1], nums[0]}; ? thanks in advance for your response.

    ReplyDelete
    Replies
    1. nvm, i figured it out -_-

      Delete
    2. Because nums[1] -> 2. Value
      nums[2] -> 3. Value
      nums[0] -> 1. Value
      But wenn we make as you say, result is others
      nums[2] -> 3. Value
      nums[1] -> 2. Value
      nums[0] -> 1. Value
      This is for reverse

      Delete
  3. public int[] rotateLeft3(int[] nums) {


    int temp=nums[0];
    nums[0]=nums[2];
    nums[2]=temp;

    int temp2=nums[0];
    nums[0]=nums[1];
    nums[1]=temp2;

    return nums;

    }

    ReplyDelete
  4. int temp = nums[0];

    nums[0] = nums[1];
    nums[1] = nums[2];
    nums[2] = temp;

    return nums;

    ReplyDelete
  5. public int[] rotateLeft3(int[] nums) {
    int arr[] = new int[3];
    arr[0] = nums[1];
    arr[1] = nums[2];
    arr[2] = nums[0];
    return arr;
    }

    ReplyDelete
  6. def rotate_left3(nums):
    list = [nums[1], nums[2], nums[0]]
    return list

    ReplyDelete
  7. how does the left rotate works here?why do we arrange like this in order ,plz anyone can explain

    ReplyDelete
  8. public int[] rotateLeft3(int[] nums) {
    int p1 = 0;

    for(int p2 = 1; p2 < nums.length; p2++){
    int temp = nums[p1];
    nums[p1++] = nums[p2];
    nums[p2] = temp;
    }

    return nums;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact