You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When an array is given, rotate the array by k steps.
example
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Approach
First, flip the elements in array right and left.
If nums = [1,2,3,4,5,6], the fliped nums is [6,5,4,3,2,1].
Then divide left, right portion by k, [6,5] [4,3,2,1] (k is 2 in this case).
Swap each portion. [5,6] [1,2,3,4].
The code is below
constrotate=function(nums,k){k=k%nums.length;// Swap all elements.letleft=0;letright=nums.length-1;while(left<right){swap(nums,left,right);left+=1;right-=1;}// Swap left portion elements.left=0;right=k-1;while(left<right){swap(nums,left,right);left+=1;right-=1;}// Swap right portion elements.left=k;right=nums.length-1;while(left<right){swap(nums,left,right);left+=1;right-=1;}};functionswap(nums,i,j){consttemp=nums[i];nums[i]=nums[j];nums[j]=temp;}
The text was updated successfully, but these errors were encountered:
Problem
When an array is given, rotate the array by k steps.
Approach
First, flip the elements in array right and left.
If nums = [1,2,3,4,5,6], the fliped nums is [6,5,4,3,2,1].
Then divide left, right portion by k, [6,5] [4,3,2,1] (k is 2 in this case).
Swap each portion. [5,6] [1,2,3,4].
The code is below
The text was updated successfully, but these errors were encountered: