Rotate an array of n elements to the right by K steps.
for example, With n = 7 and k = 3 , the Array [1,2,3,4,5,6,7" is rotated To [5,6,7,1,2,3,4] .
Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem.
[Show hint]
Hint:
Could do it in-place with O (1) extra space?
Related Problem:reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Problem Solving Analysis:
For this can be used to divide and conquer the method, you can use the given K value to divide the series into two parts,
Each part is reversed, and then the entire inverse is placed.
The principle of the algorithm to implement the inverse:
A ^= b
b ^= A
A ^= b
#-*-Coding:utf-8-*-__author__ = ' Jiuzhang ' class solution (object): def rotate (self, nums, K): n = Len (nums)
k%= n self.reverse (nums, 0, N-k) self.reverse (Nums, N-k, N) self.reverse (nums, 0, N) def reverse (sel F, Nums, start, end): For x in range (start, (start + end)/2): nums[x] ^= Nums[start + end-x-1] Nums[star T + end-x-1] ^= nums[x] nums[x] ^= Nums[start + end-x-1]
(leetcode) Rotate Array---inverse arrays