力扣189. 轮转数组

Problem: 189. 轮转数组

文章目录

题目描述

思路

思路1:利用辅助数组

利用题目所的一个规律(nums[i+k] % nums.length) (现在的数组) = nums[i] (以前的数组),则我们利用一个辅助数组将轮转后的数字存入到指定位置,然后再将其赋值给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--;
        }
    }
};
相关推荐
Two_brushes.43 分钟前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
森焱森3 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack5 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
写个博客5 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠5 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie988946 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
杰克尼6 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
.30-06Springfield7 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦7 小时前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt
xiaolang_8616_wjl7 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20