Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

mjk study log

[Leetcode] 189. Rotate Array 본문

Leetcode

[Leetcode] 189. Rotate Array

mjk- 2025. 3. 19. 17:07

문제

Given an integer array nums, 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]
 
Constraints:
1 <= nums.length <= 105-231 <= nums[i] <= 231 - 10 <= 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?

 

풀이

 

핵심은 array를 옮긴다는 것은 3번의 swap을 사용한다는 것이다. 

k를 중심으로 그 전, 그 후, 그리고 전체를 반전시켜주면 된다.

 

이때 k의 modular value 를 찾아주어야 index out-of-bound error를 피할 수 있다.

(arraySize가 7일 때 7번 옮기면 제자리가 되므로)

 

 

코드

 

void swapArray(int* nums, int start, int end) {
    for(int i = start, j = end; i<j; i++,j--) {
        nums[i]^=nums[j]^=nums[i]^=nums[j];
    }
}
void rotate(int* nums, int numsSize, int k) {
    k = k % numsSize;

    swapArray(nums, 0, numsSize-k-1);
    swapArray(nums, numsSize-k, numsSize-1);
    swapArray(nums, 0, numsSize-1);
}