Rotate Array, rotatearray
The questions are as follows:
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[5,6,7,1,2,3,4].
Method 1:
var rotate = function(nums, k) { var temp; for (var i = 0; i < k ; i++) { temp = nums.pop(); nums.unshift(temp); }};This method is simple, but the time complexity is a bit high.
Method 2:
var rotate = function(nums, k) { var tNums = new Array(); var len = nums.length; for (var i = 0; i < len; i++) { tNums[i] = nums[i]; } for (var j = 0; j < len; j++) { nums[(j + k)%len] = tNums[j]; }};
In the second method, the time complexity is reduced, but the space complexity increases.
Method 3 (refer to self-clicking to open the link ):
Var rotate = function (nums, k) {<span style = "white-space: pre"> </span> var len = nums. length; var temp = nums [0]; // var startIndex = 0; var currentIndex = 0; for (var I = 0; I <len; I ++) {currentIndex = (currentIndex + k) % len; var swap = nums [currentIndex]; nums [currentIndex] = temp; temp = swap; // complete the switching of a ring if (currentIndex = startIndex) {currentIndex = ++ startIndex; temp = nums [currentIndex] ;}};The time and space complexity of this method is very low.