Rotate Array, rotatearray

Source: Internet
Author: User

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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.