leetcode python3 简单题189. Rotate Array

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第一百八十九题

(1)题目
英文:
Given an array, rotate the array to the right by k steps, where k is non-negative.

Follow up:

Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-array

(2)解法
① 切片操作
(耗时:40ms,内存:13.9M)

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        n=len(nums)
        k%=n
        nums[:]=nums[n-k:]+nums[:n-k]

注意:
1.这里k%=n是为了:当k小于n时,k都是k;但当k>n的时候,就开始重复旋转了;特别的,当k=n时,数组与原数组是一样的。
2.nums[:0]为[]空,nums[:-1]为nums[0],nums[:-2]为[]空.

② 插入操作
(耗时:132ms,内存:14.1M)

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        n = len(nums)
        k %= n
        for _ in range(k):
            nums.insert(0, nums.pop())

猜你喜欢

转载自blog.csdn.net/qq_37285386/article/details/105939129
今日推荐