[Leetcode] [simple] [189] [JavaScript] rotating array

 

Title Description

189. rotating array

Given an array, the elements of the array to the right by k positions, wherein k is non-negative.

Example 1:

Input: [6, 7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotation to the right Step 1: [7,1 1,2,3,4,5,6]
rotates two steps to the right: [6,7,1,2,3,4,5]
rotation to the right step 3: [5,6,7,1,2,3 , 4]

Example 2:

Input: [-1, -100,3,99] and k = 2
Output: [3,99, -1, -100]
Explanation:
rotation to the right Step 1: [99, -1, -100,3]
to right rotation step 2: [3,99, -1, -100]


Description:

As far as possible to come up with more solutions, there are at least three different ways to solve this problem.
It requires space complexity is O (1) algorithm situ.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/rotate-array
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

answer:

 

Solution 1:

Cyclic pop () and the unshift () ,

 

var rotate = function(nums, k) {
    let i = 0
    while(i < k){
        nums.unshift(nums.pop())
        i++
    }
};

 

Solution 2:

You can also splice () throughout the k th element of the tail was cut, use ... expand after unshift ()

 

var rotate = function(nums, k) {
    let len = nums.length
    return nums.unshift(...nums.splice(len-k,k))
};

 

Guess you like

Origin www.cnblogs.com/2463901520-sunda/p/11456546.html