-
[알고리즘] Rotate Array■ Algorithm 2022. 8. 2. 23:52
문제 출처: https://leetcode.com/problems/rotate-array/
Rotate Array - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 해석
배열 하나가 주어졌을 때, 배열안의 요소들을 오른쪽으로 K번씩 이동시켜라. (K는 양수이다)
풀이
k번씩 오른쪽으로 한칸씩 이동한다고 할 때, nums.length 만큼 이동하면 다시 원위치로 돌아오게 된다.
따라서 k % nums.length가 실제 이동 횟수라고 볼 수 있다.
이제 배열을 수정해야하는데, 처음에 내가 실수한건 당연히 nums를 리턴한다고 생각해서 slice를 이용해 리턴했다.
var rotate = function(nums, k) { const start = nums.length - (k % nums.length); return [...nums.slice(start, nums.length), ...nums.slice(0, start)] };
vscode에서 먼저 구현한 뒤에 복붙해서 테스트해보는 편인데, 당연히
console.log(rotate([1,2,3,4,5,6,7], 3))이렇게 실행하면 정답이 리턴되었지만, 실제 사이트에서 submit하면 nums가 그대로 나와버렸다.
사이트가 잘못된건가 싶었지만 코드 구현하는 창에 보면 아래와 같이 나와있다.
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/다시 정렬된 배열을 리턴하는게 아닌, 주어진 배열(nums)의 요소들을 수정해야 했다.
var rotate = function(nums, k) { const start = nums.length - (k % nums.length); const rotated = [...nums.slice(start, nums.length), ...nums.slice(0, start)] nums.forEach((num, idx) => { nums[idx] = rotated[idx] }) };
'■ Algorithm' 카테고리의 다른 글
[알고리즘] #Two Sum II - Input Array Is Sorted (0) 2022.08.05 [알고리즘] #Move Zeroes (0) 2022.08.03 [알고리즘] #Squares of a Sorted Array (0) 2022.08.02 [알고리즘] #Search Insert Position (0) 2022.08.01 [알고리즘] #First Bad Version (0) 2022.08.01