Last active
September 3, 2021 12:41
-
-
Save AshishKapoor/54bd429bf0c9c0732870ced4053ca522 to your computer and use it in GitHub Desktop.
Array rotation solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @param {number} k | |
* @return {void} Do not return anything, modify nums in-place instead. | |
*/ | |
// using unshift and pop method (Good for first run) | |
var rotateByUnshift = function(nums, k) { | |
k = k > nums.length ? k - nums.length : k; | |
for(var i=0;i<k;i++){ | |
nums.unshift(nums.pop()); | |
} | |
return nums; | |
}; | |
// using prototype unshift, slice, and apply (Accepted) | |
var rotateByApply = function(nums, k) { | |
k %= nums.length; | |
if (k !== 0){ | |
var tmp = nums.slice(-k); | |
nums.splice(-k, k); | |
Array.prototype.unshift.apply(nums, tmp); | |
} | |
return nums; | |
}; | |
// console.log(rotateByUnshift([7,2,1,3,4,5], 3)) | |
// console.log(rotateByApply([7,2,1,3,4,5], 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment