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]}; }
package com.array1;
ReplyDeletepublic 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;
}
}
rubbish solve!!
Deletehey, 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.
ReplyDeletenvm, i figured it out -_-
DeleteBecause nums[1] -> 2. Value
Deletenums[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
public int[] rotateLeft3(int[] nums) {
ReplyDeleteint temp=nums[0];
nums[0]=nums[2];
nums[2]=temp;
int temp2=nums[0];
nums[0]=nums[1];
nums[1]=temp2;
return nums;
}
int temp = nums[0];
ReplyDeletenums[0] = nums[1];
nums[1] = nums[2];
nums[2] = temp;
return nums;
public int[] rotateLeft3(int[] nums) {
ReplyDeleteint arr[] = new int[3];
arr[0] = nums[1];
arr[1] = nums[2];
arr[2] = nums[0];
return arr;
}
Need the code in Python
ReplyDeletedef rotate_left3(nums):
ReplyDeletelist = [nums[1], nums[2], nums[0]]
return list
how does the left rotate works here?why do we arrange like this in order ,plz anyone can explain
ReplyDeletepublic int[] rotateLeft3(int[] nums) {
ReplyDeleteint p1 = 0;
for(int p2 = 1; p2 < nums.length; p2++){
int temp = nums[p1];
nums[p1++] = nums[p2];
nums[p2] = temp;
}
return nums;
}