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 you can, there are at least 3 different ways to solve this problem.
Hint:
Could you 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
解题分析:
对于这个可以利用分治方法,可以利用给出的 k 值将数列分成两部分,
分别对其中的每一部分进行逆置,然后再把整个逆置一下。
实现逆置的算法原理:
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(self, nums, start, end): for x in range(start, (start + end) / 2): nums[x] ^= nums[start + end - x - 1] nums[start + end - x - 1] ^= nums[x] nums[x] ^= nums[start + end - x - 1]
时间: 2024-11-03 03:02:52