Rotate right by k
Java
Medium
5 views
Problem Description
Task: rotate the array to the right by k steps without extra array. Use reverse trick.
Output Format
In-place update
Constraints
k can be bigger than n.
Official Solution
static void rotateRight(int[] a,int k){int n=a.length;if(n==0) return;k%=n;if(k<0) k+=n;rev(a,0,n-1);rev(a,0,k-1);rev(a,k,n-1);}static void rev(int[] a,int l,int r){while(l<r){int t=a[l];a[l]=a[r];a[r]=t;l++;r--;}}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!