LeetCode 189. 旋转数组 Rotate Array

简介: LeetCode 189. 旋转数组 Rotate Array

LeetCode 189. 旋转数组 Rotate Array


Table of Contents

中文版:

英文版:

My answer:

解题报告:

中文版:

给定一个数组,将数组中的元素向右移动 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) 的 原地 算法。

英文版:

Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:  
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
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?

My answer:

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        k = k % n
        # 上一步是为了 Corner case: [1,2,3,4,5,6]   k = 11 的情况
        self.helper(nums,0, n-k-1)
        self.helper(nums,n-k,n-1)
        self.helper(nums,0,n-1)
    def helper(self,nums,start,end):
        while start < end:
            temp =  nums[start]
            nums[start] = nums[end]
            nums[end] = temp
            start += 1
            end -= 1
        # print(nums)
"""
知识点:
1、nums[0:n-k-1] 截取 list 片段是新生成一个 list,不改变原来的list
"""

解题报告:

例子:[1,2,3,4,5,6,7]  k = 3

三步翻转法:

1、翻转 0 到 n-k-1: 4321 567

2、翻转 n-k 到 n-1: 4321 765

3、翻转 0 到 n-1:  5671234

此方法同样适用于翻转字符串题目。

相关文章
|
1天前
力扣随机一题 哈希表 排序 数组
力扣随机一题 哈希表 排序 数组
5 1
|
1天前
|
存储 算法
力扣每日一题 6/20 数学+数组
力扣每日一题 6/20 数学+数组
5 1
|
1天前
|
缓存
力扣每日一题 6/14 动态规划+数组
力扣每日一题 6/14 动态规划+数组
6 1
|
6天前
|
存储 安全 算法
C++的内置数组和STL array、STL vector
C++的内置数组和STL array、STL vector
|
1天前
|
算法 索引
力扣随机一题 位运算/滑动窗口/数组
力扣随机一题 位运算/滑动窗口/数组
9 0
|
1天前
|
算法 索引
力扣每日一题 6/28 动态规划/数组
力扣每日一题 6/28 动态规划/数组
5 0
|
1天前
力扣随机一题 6/28 数组/矩阵
力扣随机一题 6/28 数组/矩阵
4 0
|
1天前
|
索引
力扣随机一题 6/26 哈希表 数组 思维
力扣随机一题 6/26 哈希表 数组 思维
5 0
|
1天前
|
存储 算法 索引
力扣每日一题 6/24 模拟 数组 单调栈
力扣每日一题 6/24 模拟 数组 单调栈
5 0
|
1天前
|
存储 安全
力扣每日一题 6/21 数组
力扣每日一题 6/21 数组
4 0