-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotateArray.py
50 lines (35 loc) · 1.06 KB
/
RotateArray.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
'''
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and 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]
Compute in O(n) time complexity and O(1) space complexity.
Given solution is by juggling approach.
'''
def computeGCD(x, y):
while(y):
x, y = y, x % y
return x
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k=k%len(nums)
if k==0:
return nums
n=len(nums)
g=computeGCD(k,n)
for i in range(0,g):
t=j=n-i-1
temp=nums[t]
while True:
nums[j]=nums[(j-k)%n]
if (j-k)%n == t:
break
j=(j-k)%n
nums[j]=temp