Sunday 17 July 2016

Rotate Array

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

 void reverse(int *arr, int low, int high){  
   int temp;  
   while(low < high){  
     temp = arr[low];  
     arr[low] = arr[high];  
     arr[high] = temp;  
     low++;  
     high--;  
   }  
 }  
 void rotate(int* nums, int numsSize, int k) {  
   k = numsSize - k % numsSize;  
   reverse(nums, 0, k - 1);  
   reverse(nums, k, numsSize - 1);  
   reverse(nums, 0, numsSize - 1);  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive