Leetcode - Rotate Array
Problem,#
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]
Constraints:
1 <= nums.length <= 10^5
-231 <= nums[i] <= 231 - 1
0 <= k <= 10^5
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?
Solution,#
์, ๋ฐฐ์ด [1,2,3,4,5,6,7]
๋ฅผ ์ ์ดํด๋ณด์. k=3
์ผ ๋, ๊ฒฐ๊ณผ๊ฐ [5,6,7,1,2,3,4]
๋ผ๋ฉด, 1,2,3,4
์ 5,6,7
์ ๋ฐ๋ก ๋๊ณ ์๊ฐํ ์ ์์ ๊ฒ์ด๋ค.
๊ทธ๋ ๋ค๋ฉด, ๊ทน๊ฐ์ ๊ผผ์๋ฅผ ๋ถ๋ ค๋ณผ ์ ์๋ค. ์๋ํ๋ฉด, ์ ๋ด๋ผ. “Rotate” ๋ผ๊ณ ํ์ง ์๋๊ฐ. ์ผ๋จ ๋ค์ง๊ณ ์๊ฐํด๋ณด์.
[7,6,5,4,3,2,1]
๋ฅผ ์ ๋ณด๋ฉด ํด๋ต์ด ๋ณด์ธ๋ค. ๋ฐ๋ก k=3
์ด๋ผ๋ ์ ์์, ์ฐ๋ฆฌ๋ ์ด ๋ค์ง์ด์ง ๋ฐฐ์ด์ ๋ ๋ฒ๋ง ๋ ๋ค์ง์ผ๋ฉด ๋๋๋ค. ์ด๋ ๊ธฐ์ ์ผ๋ก? k=3
์ฆ, k - 1
์ ๊ธฐ์ค์ผ๋ก.
๊ทธ๋ฐ๋ฐ, ๋๋๊ฒ๋ k
๋ 10^5
๊น์ง ์
๋ ฅ์ ๋ฐ์ ์ ์๋ค. ์ฆ, nums.length
๋ณด๋ค ๋ ํด ์ ์๋ค. ์ด๋ฌ๋ฉด ๋น์ฐํ ์๋ฌ๊ฐ ๋ฐ์ํ๋ค. ๋๋จธ์ง ์ฐ์ฐ์ ํตํด์ N๊ฐ๋ณด๋ค ํด ๋ ์ธ์ ๋ N๊ฐ์ผ๋ก ๋๋ ๋๋จธ์ง, ์ฆ ์ค์ ์ฐ๋ฆฌ๊ฐ ํ์ ์์ผ์ผ ํ๋ ์๋ง ๋ฝ์๋ผ ์ ์๋ค.
class Solution {
public void rotate(int[] nums, int k) {
if (nums.length == 1 || k == nums.length) {
return;
}
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k % nums.length - 1);
reverse(nums, k % nums.length, nums.length - 1);
}
private void reverse(int[] n, int l, int r) {
while (l < r) {
int tmp = n[l];
n[l] = n[r];
n[r] = tmp;
++l;
--r;
}
}
}
์ฐธ๊ณ ๋ก ์ด ์ ๊ทผ๋ฒ์ ์์ฒญ๋ ๋ ผ์์ ์ผ๊ธฐ์ํจ ๋ฐฉ๋ฒ์ด์๋ค.. ์ด ๊ธ ์ฐ๋ฉด์ Solution ๋ณด๊ณ ์์๋ค.