JonnyF--Rotate Array
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.
解题思路:
这道题是将包含n个元素的数组向右旋转k步,例如,数组[1,2,3,4,5,6,7]包含元素个数n = 7,向右旋转k = 3步,得到[5,6,7,1,2,3,4]。这里我使用的是通过切片的方式将切完后的数组再重新拼接起来。
class Solution: # @param nums, a list of integer # @param k, num of steps # @return nothing, please modify the nums list in-place. def rotate(self, nums, k): n = len(nums) if n > 1 and k >0: self.nums = nums[n-k:] + nums[:n-k] for x in range(n): nums[x] = self.nums[x]

浙公网安备 33010602011771号