Since I'm practicing basic array problem in java. I had a problem about rotate n elements by k unit to left/right.
I know how to deal with small elements array, such as I have an array int[]arr={1,2,3};
I can just switch the position of the elements like this:
return new int[]{arr[1],arr[2],arr[0]};
After this if I got 100 or more elements in an array this way does not work at all. So I saw someone use reverse method to deal with it.
public void rotateProblem(int[]arr,int k){ //k means rotate k units to right
k%=arr.length;
k=2;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
}
But I don't get it at all how does this method reverse the array, and why do I need use k%=arr.length;
Can anyone explain to me the reverse method?