力扣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--;
        }
    }
};
相关推荐
嘴贱欠吻!3 小时前
Flutter鸿蒙开发指南(七):轮播图搜索框和导航栏
算法·flutter·图搜索算法
张祥6422889043 小时前
误差理论与测量平差基础笔记十
笔记·算法·机器学习
踩坑记录3 小时前
leetcode hot100 2.两数相加 链表 medium
leetcode·链表
qq_192779873 小时前
C++模块化编程指南
开发语言·c++·算法
cici158745 小时前
大规模MIMO系统中Alamouti预编码的QPSK复用性能MATLAB仿真
算法·matlab·预编码算法
历程里程碑5 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
2501_940315267 小时前
航电oj:首字母变大写
开发语言·c++·算法
CodeByV7 小时前
【算法题】多源BFS
算法
TracyCoder1237 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
浒畔居7 小时前
泛型编程与STL设计思想
开发语言·c++·算法