美文网首页
189. 轮转数组(中等)-普通数组

189. 轮转数组(中等)-普通数组

作者: MatrixZ | 来源:发表于2023-05-21 08:38 被阅读0次

给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
使用空间复杂度为 O(1) 的 原地 算法

分析

  • 这个有点像翻转单词,但是只是两个单词
  • 但是思想一样,可以先总体翻转,在单独翻转
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        def reverse(nums, start, end):
            
            while start < end:
                nums[start], nums[end] = nums[end], nums[start]
                start += 1
                end -= 1
        
        n = len(nums)
        k %= n
        reverse(nums, 0, n - 1)
        
        reverse(nums, 0, k - 1)
        # 陷阱1, 闭区间是包含边界的
        reverse(nums, k, n - 1)


相关文章

  • 63.轮转数组

    day:14 189. 轮转数组[https://leetcode-cn.com/problems/rotate...

  • LeetCode:189. 轮转数组

    问题链接 189. 轮转数组[https://leetcode-cn.com/problems/rotate-ar...

  • 189. 轮转数组

    题目地址(189. 轮转数组) https://leetcode.cn/problems/rotate-array...

  • 189. 轮转数组

    https://leetcode.cn/problems/rotate-array/[https://leetco...

  • 189. 轮转数组

    1.题目 给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 示例 1:输入: nums = ...

  • LeetCode 189. 轮转数组

    题目 给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 例:输入: nums = [1,2,...

  • 189. 旋转数组

    189. 旋转数组[https://leetcode-cn.com/problems/rotate-array/]...

  • 算法:旋转数组

    189. 旋转数组[https://leetcode-cn.com/problems/rotate-array/]...

  • LeetCodeDay02

    189. 旋转数组 描述 将包含 n 个元素的数组向右旋转 k 步。 例如,如果 n = 7 , k = 3,...

  • 2022-04-26 「189. 轮转数组」

    今日中等题:https://leetcode-cn.com/problems/rotate-array/[http...

网友评论

      本文标题:189. 轮转数组(中等)-普通数组

      本文链接:https://www.haomeiwen.com/subject/lnjasdtx.html