Given an array, rotate the array to the right by k steps, where k is non-negative.
Example
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]
Solution
def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
flag = [True] * len(nums)
for i in range(len(nums)) :
if flag[i]:
value = nums[i]
while flag[(i+k) % len(nums)]:
j = (i+k) % len(nums)
temp = nums[j]
nums[j] = value
i = j
value = temp
flag[j] = False