mjk study log
[Leetcode] 189. Rotate Array 본문
문제
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);
}
'Leetcode' 카테고리의 다른 글
[Leetcode] 394. Decode String (0) | 2025.03.19 |
---|---|
[Leetcode] 328. Odd Even Linked List (0) | 2025.03.19 |
[Leetcode] 128. Longest Consecutive Sequence (0) | 2025.03.19 |
[Leetcode] 97. Interleaving String (0) | 2025.03.17 |
[Leetcode] 1019. Next Greater Node In Linked List (0) | 2025.03.17 |