์ƒˆ์†Œ์‹

IN DEPTH CAKE/Supercoder

[์ฝ”๋”ฉ/LeetCode150-(6)] Rotate Array (189)

  • -
๋ฐ˜์‘ํ˜•

 

๋ณธ ๊ธ€์€ LeetCode Top Interview 150์— ์ •๋ฆฌ๋œ ๋ฌธ์ œ๋ฅผ ์š”์•ฝํ•˜๊ณ  ์ด์— ๋Œ€ํ•œ ๊ฐœ์ธ์ ์ธ ํ’€์ด๋ฅผ ํฌํ•จํ•˜๊ณ ์žˆ์Šต๋‹ˆ๋‹ค.
๋ณธ ํฌ์ŠคํŒ… ์‹œ๋ฆฌ์ฆˆ๋Š” 150 list์˜ ์ˆœ์„œ๋ฅผ ๋”ฐ๋ผ์„œ ๊ฒŒ์žฌ๋ฉ๋‹ˆ๋‹ค. ํ’€์ด ์–ธ์–ด๋Š” python3์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

 

 

 

 

๋‚œ์ด๋„: Medium

ํ‚ค์›Œ๋“œ: Array

 

 

๋ฌธ์ œ ์›๋ฌธ: https://leetcode.com/problems/rotate-array/description/?envType=study-plan-v2&envId=top-interview-150 

 

์ •์ˆ˜ ๋ฐฐ์—ด nums๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ ์ฃผ์–ด์ง„ ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜ k์— ๋Œ€ํ•ด์„œ k ๋ฒˆ๋งŒํผ ๋ฐฐ์—ด์„ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ํšŒ์ „์‹œ์ผœ๋ผ

 

๐Ÿงช ์˜ˆ์ œ 

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]

 

๐Ÿ” ๋ฌธ์ œ ํ’€์ด

์ถ”๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•œ ๋ฐฉ๋ฒ•. ๋ฐฐ์—ด์˜ rotation์€ (i + k) % len(nums) ๋กœ indexingํ•˜์—ฌ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

Runtime complexity : O(N)

Memory complexity : O(N)

 

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        N = len(nums)
        tmp = [0] * N
        for i in range(N):
            tmp[(i+k) % N] = nums[i]
        nums[:] = tmp

 

๐ŸŒก Follow up

- in-place๋ฅผ O(1) extra space์œผ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€?

 

 

๋ฐ˜์‘ํ˜•
Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.

# ๋กœ๋”ฉ ํ™”๋ฉด ๋™์ž‘ ์ฝ”๋“œ(Code) ์„ค์ •ํ•˜๊ธฐ