leetcode - 189. Rotate Array

Description

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Example 1:

复制代码
Input: nums = [1,2,3,4,5,6,7], 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: nums = [-1,-100,3,99], 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]

Constraints:

复制代码
1 <= nums.length <= 10^5
-2^31 <= nums[i] <= 2^31 - 1
0 <= k <= 10^5

Follow up:

复制代码
Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
Could you do it in-place with O(1) extra space?

Solution

Solved after help...

For a space o ( 1 ) o(1) o(1) solution, one straightforward way is: start with 0, use current value to set the new index, and then update the current value with the original value in the new index, and keep going until we replaced all the numbers.

This works for most cases, but doesn't work when k = k % n, for example, when n=4 and k=2, if we start with 0, then we jump to 2, then we jump back to 0. This could create a loop.

To avoid this loop, before starting, we should keep track of where we started, and once we found we arrived at start again, we increase start by 1 and keep going.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        k %= len(nums)
        rotate_cnt = 0
        start = 0
        while rotate_cnt < len(nums):
            new_index, value_to_set = start, nums[start]
            while True:
                new_index = (new_index + k) % len(nums)
                ori_value = nums[new_index]
                nums[new_index] = value_to_set
                value_to_set = ori_value
                rotate_cnt += 1
                if new_index == start:
                    break
            start += 1
相关推荐
sprintzer25 分钟前
12.06-12.15力扣分治法刷题
算法·leetcode
月明长歌25 分钟前
【码道初阶】【牛客BM30】二叉搜索树与双向链表:java中以引用代指针操作的艺术与陷阱
java·数据结构·算法·leetcode·二叉树·笔试·字节跳动
刃神太酷啦35 分钟前
Linux 进程核心原理精讲:从体系结构到实战操作(含 fork / 状态 / 优先级)----《Hello Linux!》(6)
java·linux·运维·c语言·c++·算法·leetcode
小李小李快乐不已36 分钟前
数组&&矩阵理论基础
数据结构·c++·线性代数·算法·leetcode·矩阵
SiYuanFeng42 分钟前
新手leetcode快速刷题指南
算法·leetcode·职场和发展
长安er42 分钟前
LeetCode 77/216/22组合型回溯法-组合 / 组合总和 III / 括号生成)
数据结构·算法·leetcode·剪枝·回溯
菜鸟233号1 小时前
力扣98 验证二叉搜索树 java实现
java·数据结构·算法·leetcode
循着风2 小时前
环形子数组的最大和
数据结构·算法·leetcode
yaoh.wang2 小时前
力扣(LeetCode) 9: 回文数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
小年糕是糕手2 小时前
【C/C++刷题集】类和对象算法题(一)
数据结构·c++·程序人生·考研·算法·leetcode·改行学it