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); } };
k
가nums
의 길이보다 큰 경우 한 바퀴 이상 돌아 원래 상태가 되므로k
를nums
의 길이로 나눈 나머지를 구해서 그 수만큼 배열 요소를 이동시키면 됨.나눈 나머지가
0
일 때는 원위치이므로 건드릴 필요가 없음.