-
[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)'알고리즘' 카테고리의 다른 글
[LeetCode] 167. Two Sum II - Input Array Is Sorted (0) 2022.04.24 [LeetCode] 283. Move Zeroes (0) 2022.04.24 [LeetCode] 977. Squares of a Sorted Array (0) 2022.04.24 [LeetCode] # 35. Search Insert Position (0) 2022.04.24 [LeetCode] 278. First Bad Version (0) 2022.04.24