LeetCode 코딩 문제 2021/06/15 - Rotate Array

이호현·2021년 6월 15일
0

Algorithm

목록 보기
123/138

[문제]

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

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]

(요약) 배열 끝 요소를 하나씩 떼서 앞에 붙이는데 k만큼 반복하고 만들어진 배열을 return (함수에서 배열을 return하지 말고 nums만 수정해라)

[풀이]

var rotate = function(nums, k) {
  const moves = k % nums.length;

  if(moves) {
    const spliceArr = nums.splice(-1 * moves);
    nums.unshift(...spliceArr);
  }
};

knums의 길이보다 큰 경우 한 바퀴 이상 돌아 원래 상태가 되므로 knums의 길이로 나눈 나머지를 구해서 그 수만큼 배열 요소를 이동시키면 됨.

나눈 나머지가 0일 때는 원위치이므로 건드릴 필요가 없음.

profile
평생 개발자로 살고싶습니다

0개의 댓글