力扣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--;
        }
    }
};
相关推荐
菜鸟求带飞_9 分钟前
算法打卡:第十一章 图论part01
java·数据结构·算法
浅念同学11 分钟前
算法.图论-建图/拓扑排序及其拓展
算法·图论
是小Y啦27 分钟前
leetcode 106.从中序与后续遍历序列构造二叉树
数据结构·算法·leetcode
程序猿练习生32 分钟前
C++速通LeetCode中等第9题-合并区间
开发语言·c++·leetcode
liuyang-neu37 分钟前
力扣 42.接雨水
java·算法·leetcode
y_dd1 小时前
【machine learning-12-多元线性回归】
算法·机器学习·线性回归
m0_631270401 小时前
标准c语言(一)
c语言·开发语言·算法
万河归海4281 小时前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio
小周的C语言学习笔记1 小时前
鹏哥C语言36-37---循环/分支语句练习(折半查找算法)
c语言·算法·visual studio
y_dd1 小时前
【machine learning-七-线性回归之成本函数】
算法·回归·线性回归