LeetCode--189--旋转数组

问题描述:

给定一个数组,将数组中的元素向右移动 个位置,其中 是非负数。

示例 1:

输入: [1,2,3,4,5,6,7]k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]

示例 2:

输入: [-1,-100,3,99]k = 2
输出: [3,99,-1,-100]
解释: 
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]

方法1:1234567  k = 2 step1:54321 76 ;step2:6712345

 1 class Solution(object):
 2     def rotate(self, nums, k):
 3         """
 4         :type nums: List[int]
 5         :type k: int
 6         :rtype: void Do not return anything, modify nums in-place instead.
 7         """
 8         width = len(nums)
 9         if width == 0 or width == 1:
10             nums = []
11             return
12         if width == k:
13             return
14         nums[width - k:] = nums[:width-k-1:-1]
15         nums[:width - k ] = nums[width - k - 1::-1]
16         nums.reverse()

官方:

 1 class Solution(object):
 2     def rotate(self, nums, k):
 3         """
 4         :type nums: List[int]
 5         :type k: int
 6         :rtype: void Do not return anything, modify nums in-place instead.
 7         """
 8         n=len(nums)
 9         if n<2 or k==0:
10             return 
11         k=k%n
12         nums[:k],nums[k:]=nums[n-k:],nums[:n-k]

官方二:

1 class Solution(object):
2     def rotate(self, nums, k):
3         """
4         :type nums: List[int]
5         :type k: int
6         :rtype: void Do not return anything, modify nums in-place instead.
7         """ 
8         k = k % len(nums)
9         nums[:]=nums[-k:]+nums[:-k]

2018-09-15 11:57:25

猜你喜欢

转载自www.cnblogs.com/NPC-assange/p/9650572.html