力扣189. 轮转数组

Problem: 189. 轮转数组

文章目录

题目描述

思路

思路1:利用辅助数组

利用题目所的一个规律(numsi+k % nums.length) (现在的数组) = numsi (以前的数组),则我们利用一个辅助数组将轮转后的数字存入到指定位置,然后再将其赋值给nums

思路2:原地翻转数组

先将数组整个反转,再将索引位置为0 \~ k m o d mod mod n - 1位置的元素反转(其中 n n n为数组的大小),最后将索引位置为k\~ k m o d mod mod n - 1位置的元素反转即为最终的结果

复杂度

思路1:

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为数组nums的大小

空间复杂度:

O ( n ) O(n) O(n)

思路2:

时间复杂度:

O ( n ) O(n) O(n)

空间复杂度:

O ( 1 ) O(1) O(1)

Code

cpp 复制代码
class Solution {
public:
    /**
     *
     * @param nums To be operated array
     * @param k Specifies the number of rotations
     */
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> temp(n);
        for (int i = 0; i < n; ++i) {
            temp[(i + k) % n] = nums[i];
        }
        for (int i = 0; i < n; ++i) {
            nums[i] = temp[i];
        }
    }
};
cpp 复制代码
class Solution {
public:
    /**
     * 
     * @param nums To be operated array
     * @param k Specifies the number of rotations
     */
    void rotate(vector<int> &nums, int k) {
        int n = nums.size();
        reverse(nums, 0, n - 1);
        reverse(nums,0, k % n - 1);
        reverse(nums, k % n, n - 1);
        
    }
    void reverse(vector<int>& nums, int left, int right) {
        int n = nums.size();
        while (left < right) {
            swap(nums[left], nums[right]);
            left++;
            right--;
        }
    }
};
相关推荐
To_OC9 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin1 天前
lk每日冒险题--数据结构6.27
算法
To_OC1 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
kisshyshy2 天前
从递归到迭代,一文吃透二叉树的核心知识与 JavaScript 实现
javascript·算法·代码规范
To_OC2 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode