Tuesday, October 27, 2015

Rotate Array via Javascript

Leetcode rotate array via Javascript using reversal:

 /**  
  * @param {number[]} nums  
  * @param {number} k  
  * @return {void} Do not return anything, modify nums in-place instead.  
  */  
 var rotate = function(nums, k) {  
   if(nums.length === 0) {  
    throw "provide valid array";  
   }  
      k = k % nums.length;  
    
   //length of first part  
   var a = nums.length - k;   
    
   reverse(nums, 0, a-1);  
   reverse(nums, a, nums.length-1);  
   reverse(nums, 0, nums.length-1);  
 };  
   
 function reverse(arr, left, right){  
   while(left < right){  
     var temp = arr[left];  
     arr[left] = arr[right];  
     arr[right] = temp;  
     left++;  
     right--;  
   }    
 }  

No comments: