記錄

[JS]189. Rotate Array 본문

FRONTEND STUDY/LeetCode

[JS]189. Rotate Array

prts 2022. 10. 19. 17:26

문제 링크: https://leetcode.com/problems/rotate-array/
난이도: Medium

Given an array, rotate the array to the right by k steps, where k is non-negative.

주어진 배열을 음수가 아닌 정수 k만큼 우측으로 회전시켜라.

 

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Constraints:

  • 1 <= nums.length <= 105
  • 231 <= nums[i] <= 231 - 1
  • 0 <= k <= 105

Follow up:

  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

Related Topics: Array, Math, Two Pointers

 

문제풀이

 

배열 nums에서 k만큼의 요소들을 뒤에서 앞으로 위치를 바꿔주는 방법을 찾는 문제이다.

k만큼 잘라낸 부분 내에서 따로 요소들끼리 순서가 바뀌거나 하지는 않기 때문에 k만큼 splice한 부분을 nums 에 unshift하면 된다. 아니면 nums에서 k만큼을 뺀 이후 나머지를 unshift하는 방식으로 해도 된다.

 

var rotate = function(nums, k) {
    k = k % nums.length; //if k > nums.length , k%=nums.length로 적어도 됨
    let rotate=nums.splice(nums.length-k);
    return nums.unshift(...rotate);
    // nums.unshift(...nums.splice(nums.length-k)); //한줄 버전
};
Comments