旋转数组
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 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]
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的原地算法。
代码
先用段python里面的切片方法吧
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
l = len(nums)
k = k % l
if l > 1 and k > 0:
nums[:] = nums[-k:] + nums[:-k]
切片方法真是个好东西啊,跑下下面的两个片段就知道怎么用了:
n = [1, 2, 3, 4, 5]
print(n[-3:])
print(n[-2:])
print(n[:-3])
print(n[:-2])
答案在此:
[3, 4, 5]
[4, 5]
[1, 2]
[1, 2, 3]
先这种方法吧,我再去研究研究有没有其他方法。
ok,现在再贴个很low的刚刚写出来的算法。
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
l = len(nums)
k = k % l
temp = []
temp[:] = nums[:]
for i in range(0,l):
if i+k < l:
nums[i+k] = temp[i]
else:
nums[(i+k)%l] = temp[i]
笑死了,刚刚又稍微改了下,发现从战胜52%到74%哈哈哈哈哈
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
l = len(nums)
k = k % l
temp = nums[:]
for i in range(0,l):
if i+k < l:
nums[i+k] = temp[i]
else:
nums[(i+k)%l] = temp[i]