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 ๋ณด๊ณ  ์•Œ์•˜๋‹ค.