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
相关推荐
橘颂TA14 分钟前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!1 小时前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi1 小时前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
-森屿安年-4 小时前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
元亓亓亓7 小时前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
2501_941143738 小时前
缓存中间件Redis与Memcached在高并发互联网系统优化与实践经验分享
leetcode
Elias不吃糖10 小时前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
野蛮人6号11 小时前
力扣热题100道前62道,内容和力扣官方稍有不同,记录了本人的一些独特的解法
数据结构·算法·leetcode
CoderYanger13 小时前
优选算法-栈:69.验证栈序列
java·开发语言·算法·leetcode·职场和发展·1024程序员节
2501_9418036214 小时前
Python高性能大数据分析与Pandas实战分享:海量数据处理、清洗与优化经验
leetcode