LC练习 旋转数组
1
每次旋转一步,重复k次。可行,但是速度太慢了。
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
for i in range(k):
a = nums[-1]
for j in range(length-1):
nums[-j-1] = nums[-j-2]
nums[0] = a
2
环状结构,遍历所有元素一遍
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k = k % length
count = 0 #用于记录移动次数
start = 0
while count < length: #所有元素都移动一次结束
current = start
prev = nums[current]
while True:
later = (current + k) % length
tem = nums[later]
nums[later] = prev
prev = tem
current = later
count += 1
if start == current:
break
start += 1
3
反转
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k = k % length
nums.reverse()
nums[:k] =[i for i in reversed(nums[:k])]
nums[k:] =[i for i in reversed(nums[k:])]
这里有一个问题,不知道为什么这样写在LC里不对,但是外面跑,print()是对的?
nums = list(reversed(nums))
nums[:k] = list(reversed(nums[:k]))
nums[k:] = list(reversed(nums[k:]))
print(nums)