Leetcode练习(Python):数组类:第189题:给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

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

说明:

  • 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
  • 要求使用空间复杂度为 O(1) 的 原地 算法。
思路:
本题思路简单。
程序:
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        if k == 0:
            return 
        index = k
        target = length - 1
        while k > 0:
            data = nums[target]
            nums.insert(0,nums.pop())
            k -= 1

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12767807.html
今日推荐