알고리즘

[LeetCode] 189. Rotate Array

유병각 2022. 4. 24. 17:18

풀이_#1

주기(cycle) 과 list slicing 을 활용한 풀이

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        cycle = n 

        move = k % cycle
        i = n - move

        s1 = nums[:i]
        s2 = nums[i:]
        s3 = s2 + s1

        for _ in range(n):
            nums[_] = s3[_]
import collections

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """

        queue = collections.deque(nums)
        n = len(nums)
        k %= n

        while (k > 0):
            queue.appendleft(queue.pop())
            k -= 1

        for _ in range(n):
            nums[_] = queue[_]
import collections

class Solution(object):
    def reverse(self,arr, s,f):

        while (s < f):
            temp = arr[s]
            arr[s] = arr[f]
            arr[f] = temp
            s += 1
            f -= 1

    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        cycle = k % n
        self.reverse(nums, 0, n-1)
        self.reverse(nums,0,cycle-1)
        self.reverse(nums,cycle ,n-1)