-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path189.py
65 lines (49 loc) · 1.58 KB
/
189.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'''189. Rotate Array
Created on 2024-11-28 14:03:48
2024-11-28 14:14:04
@author: MilkTea_shih
'''
#TODO: https://leetcode.wang/leetcode-189-Rotate-Array.html # do solution 3!
#%% Packages
from collections import deque
#%% Variable
#%% Functions
class Solution:
#Time: O(n) Space: O(1)
def rotate(self, nums: list[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
nums[:] = nums[-k:] + nums[:-k]
class Solution_reverse:
#Time: O(2n) Space: O(1)
def reverse(self, array: list[int], left: int, right: int) -> None:
while left < right:
array[left], array[right] = array[right], array[left]
left += 1
right -= 1
def rotate(self, nums: list[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums_length: int = len(nums)
k %= nums_length
nums.reverse() #self.reverse(nums, 0, nums_length - 1) #the same as!
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, nums_length - 1)
class Solution_myself:
#Time: O(k + n) Space: O(n)
def rotate(self, nums: list[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
temp_queue: deque[int] = deque(nums)
temp_queue.rotate(k % len(nums)) #avoid repeated rotations
for index, num in enumerate(temp_queue):
nums[index] = num
#%% Main Function
#%% Main
if __name__ == '__main__':
pass
#%%