-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path189_Rotate_Array.py
More file actions
39 lines (33 loc) · 1.11 KB
/
189_Rotate_Array.py
File metadata and controls
39 lines (33 loc) · 1.11 KB
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
# Author: cym
class Solution:
# def rotate(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: void Do not return anything, modify nums in-place instead.
# """
# if k > len(nums):
# k %= len(nums)
# tmp = nums[len(nums)-k:len(nums)]
# for i in range(len(nums)-k):
# nums[len(nums)-1-i] = nums[len(nums)-k-1-i]
# for i in range(len(tmp)):
# nums[i] = tmp[i]
# *********** reverse 3 times ***************
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
if k > length:
k %= length
self.reverse(nums, 0, length-k-1)
self.reverse(nums, length-k, length-1)
self.reverse(nums, 0, length-1)
def reverse(self, nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1