博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Rotate Array
阅读量:6165 次
发布时间:2019-06-21

本文共 1085 字,大约阅读时间需要 3 分钟。

This problem, as stated in the problem statement, has a lot of solutions. Since the problem requires us to solve it in O(1) space complexity, I only show some of them in the following.

The first one, also my favorite one, is to apply reverse to nums for three times. You may run some this code on some examples to see how it works.

1 class Solution { 2 public: 3     void rotate(vector
& nums, int k) { 4 int n = nums.size(); 5 k %= n; 6 reverse(nums.begin(), nums.begin() + n - k); 7 reverse(nums.end() - k, nums.end()); 8 reverse(nums.begin(), nums.end()); 9 }10 };

The second one is to use swap, and is translated from the C code in this link.

1 class Solution {2 public:3     void rotate(vector
& nums, int k) {4 int start = 0, n = nums.size();5 for (; k %= n; n -= k, start += k)6 for (int i = 0; i < k; i++)7 swap(nums[start + i], nums[start + n - k + i]);8 }9 };

For a more comprehensive summary of other solutions, you may refer to (it has 5 solutions).

转载地址:http://ppyba.baihongyu.com/

你可能感兴趣的文章
敏捷宣言
查看>>
php Yii: 出现undefined offset 或者 undefined index解决方案
查看>>
Bash编程入门
查看>>
org.tinygroup.binarytree-二叉树
查看>>
5.6-全栈Java笔记:内部类的四种实现方式
查看>>
Linux微职位学习笔记-终端
查看>>
自己写了一个友盟推送的util
查看>>
Mapreduce 扫描hbase表建立solr索引
查看>>
RHEL 5.8 yum本地源
查看>>
Teams 新功能更新【五月底】Busy on Busy 忙线音
查看>>
orzdba安装与使用
查看>>
二叉搜索树的插入叶子结点的递归实现方法
查看>>
通过nginx配置不同二级域名代理多个系统
查看>>
linux基础篇-23,文件系统管理
查看>>
keepalived+nginx高可用配置
查看>>
node.js爬虫爬取电影天堂,实现电视剧批量下载。
查看>>
Ubuntu 18.04.1 LTS下部署FastDFS 5.11+Nginx 1.14.0
查看>>
PHP 运行方式(PHP SAPI介绍)
查看>>
puppet学习之puppet证书验证
查看>>
Server 2008 R2 AD RMS完整部署:四、客户端篇
查看>>