Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

新题抢先刷,这道题标为 Easy,应该不是很难,我们先来看一种 O(n) 的空间复杂度的方法,我们复制一个和 nums 一样的数组,然后利用映射关系 i -> (i+k)%n 来交换数字。代码如下:

解法一:

class Solution {
public:
void rotate(vector<int>& nums, int k) {
vector<int> t = nums;
for (int i = ; i < nums.size(); ++i) {
nums[(i + k) % nums.size()] = t[i];
}
}
};

由于提示中要求我们空间复杂度为 O(1),所以我们不能用辅助数组,上面的思想还是可以使用的,但是写法就复杂的多,而且需要用到很多的辅助变量,我们还是要将 nums[idx] 上的数字移动到 nums[(idx+k) % n] 上去,为了防止数据覆盖丢失,我们需要用额外的变量来保存,这里用了 pre 和 cur,其中 cur 初始化为了数组的第一个数字,然后当然需要变量 idx 标明当前在交换的位置,还需要一个变量 start,这个是为了防止陷入死循环的,初始化为0,一旦当 idx 变到了 strat 的位置,则 start 自增1,再赋值给 idx,这样 idx 的位置也改变了,可以继续进行交换了。举个例子,假如 [1, 2, 3, 4], K=2 的话,那么 idx=0,下一次变为 idx = (idx+k) % n = 2,再下一次又变成了 idx = (idx+k) % n = 0,此时明显 1 和 3 的位置还没有处理过,所以当我们发现 idx 和 start 相等,则二者均自增1,那么此时 idx=1,下一次变为 idx = (idx+k) % n = 3,就可以交换完所有的数字了。

因为长度为n的数组只需要更新n次,所以我们用一个 for 循环来处理n次。首先 pre 更新为 cur,然后计算新的 idx 的位置,然后将 nums[idx] 上的值先存到 cur 上,然后把 pre 赋值给 nums[idx],这相当于把上一轮的 nums[idx] 赋给了新的一轮,完成了数字的交换,然后 if 语句判断是否会变到处理过的数字,参见上面一段的解释,我们用题目中的例子1来展示下面这种算法的 nums 的变化过程:

1 2 3 4 5 6 7
1 2 3 5 6 7
1 2 3 1 5 6
1 2 1 5 6 4
1 2 7 1 5 4
1 7 1 5 3 4
1 6 7 1 3 4
6 7 1 2 3 4

解法二:

class Solution {
public:
void rotate(vector<int>& nums, int k) {
if (nums.empty() || (k %= nums.size()) == ) return;
int start = , idx = , pre = , cur = nums[], n = nums.size();
for (int i = ; i < n; ++i) {
pre = cur;
idx = (idx + k) % n;
cur = nums[idx];
nums[idx] = pre;
if (idx == start) {
idx = ++start;
cur = nums[idx];
}
}
}
};

根据热心网友 waruzhi 的留言,这道题其实还有种类似翻转字符的方法,思路是先把前 n-k 个数字翻转一下,再把后k个数字翻转一下,最后再把整个数组翻转一下:

1 2 3 4 5 6 7
4 3 2 1 5 6 7
4 3 2 1 7 6 5
5 6 7 1 2 3 4

解法三:

class Solution {
public:
void rotate(vector<int>& nums, int k) {
if (nums.empty() || (k %= nums.size()) == ) return;
int n = nums.size();
reverse(nums.begin(), nums.begin() + n - k);
reverse(nums.begin() + n - k, nums.end());
reverse(nums.begin(), nums.end());
}
};

由于旋转数组的操作也可以看做从数组的末尾取k个数组放入数组的开头,所以我们用 STL 的 push_back 和 erase 可以很容易的实现这些操作。

解法四:

class Solution {
public:
void rotate(vector<int>& nums, int k) {
if (nums.empty() || (k %= nums.size()) == ) return;
int n = nums.size();
for (int i = ; i < n - k; ++i) {
nums.push_back(nums[]);
nums.erase(nums.begin());
}
}
};

下面这种方法其实还蛮独特的,通过不停的交换某两个数字的位置来实现旋转,根据网上这个帖子的思路改写而来,数组改变过程如下:

1 2 3 4 5 6 7
2 3 4 6 7
5 3 4 1 7
5 6 4 1 2
5 6 7 1 4 2 3
5 6 7 1 2 4 3
5 6 7 1 2 3 4

解法五:

class Solution {
public:
void rotate(vector<int>& nums, int k) {
if (nums.empty()) return;
int n = nums.size(), start = ;
while (n && (k %= n)) {
for (int i = ; i < k; ++i) {
swap(nums[i + start], nums[n - k + i + start]);
}
n -= k;
start += k;
}
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/189

类似题目:

Rotate List

Reverse Words in a String II

参考资料:

https://leetcode.com/problems/rotate-array/

https://leetcode.com/problems/rotate-array/discuss/54250/Easy-to-read-Java-solution

https://leetcode.com/problems/rotate-array/discuss/54277/Summary-of-C%2B%2B-solutions

https://leetcode.com/problems/rotate-array/discuss/54438/My-c%2B%2B-solution-o(n)time-andand-o(1)space

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 189. Rotate Array 旋转数组的更多相关文章

  1. 189 Rotate Array 旋转数组

    将包含 n 个元素的数组向右旋转 k 步.例如,如果  n = 7 ,  k = 3,给定数组  [1,2,3,4,5,6,7]  ,向右旋转后的结果为 [5,6,7,1,2,3,4].注意:尽可能找 ...

  2. LeetCode 189. Rotate Array (旋转数组)

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array  ...

  3. [LeetCode] Rotate Array 旋转数组

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array  ...

  4. Rotate Array 旋转数组 JS 版本解法

    Given an array, rotate the array to the right by k steps, where k is non-negative. 给定一个数组,并且给定一个非负数的 ...

  5. Leetcode 189 Rotate Array stl

    题意:将数组旋转k次,如将数组[1,2,3,4,5]旋转1次得到[2,3,4,5,1],将数组[1,2,3,4,5]旋转2次得到[3,4,5,1,2]..... 本质是将数组分成两部分a1,a2,.. ...

  6. rotate array 旋转数组

    class Solution {public: void rotate(vector<int>& nums, int k) { int n=nums.size(); int i=0 ...

  7. Java [Leetcode 189]Rotate Array

    题目描述: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the ...

  8. C#解leetcode 189. Rotate Array

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array  ...

  9. Java for LeetCode 189 Rotate Array

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array ...

随机推荐

  1. mysql float类型详解

    mysql float类型详解float类型长度必须设置3以上 不然会报错 out of range如果设置3 就只是 整数+小数的长度 比方说3.23 3.2等等 3.333就不行了 4位了

  2. 如何创建一个简单 APT 仓库

    0. 无废话版本 需求: 有一堆 .deb 包,想把它们做成一个 APT 仓库,这样就可以用apk install pkgname进行安装了,这样一方面自己可以规避 dpkg -i xxx.deb 时 ...

  3. python Condition

    import threading # 必须要使用condition的例子 # class XiaoAi(threading.Thread):# def __init__(self, lock):# s ...

  4. WPF控件模板(6)

    什么是ControlTemplate? ControlTemplate(控件模板)不仅是用于来定义控件的外观.样式, 还可通过控件模板的触发器(ControlTemplate.Triggers)修改控 ...

  5. C/C++中new的使用规则

    本人未重视new与指针的使用,终于,终于在前一天船翻了,而且没有爬上岸: 故此,今特来补全new的用法,及其一些规则: 话不多说 C++提供了一种“动态内存分配”机制,使得程序可以在运行期间,根据实际 ...

  6. 回忆C++

    内联函数 内联函数适用于函数较为短小的情况. 内联函数存在的意义是:提高程序运行效率. 内联函数的缺点:如果一个内联函数太长且频繁调用,会导致生成的可执行程序较大. 静态链接库会被嵌入到生成的可执行程 ...

  7. java SSM 框架 微信自定义菜单 快递接口 SpringMVC mybatis redis shiro ehcache websocket

    A 调用摄像头拍照,自定义裁剪编辑头像,头像图片色度调节B 集成代码生成器 [正反双向](单表.主表.明细表.树形表,快速开发利器)+快速表单构建器 freemaker模版技术 ,0个代码不用写,生成 ...

  8. Arduino控制舵机

    一.接线 舵机 Arduino GND GND +5V 5V PWN 10 其中信号线PWN接arduino上任意带波浪号的引脚都可,我这里选择的是10号引脚,注意在程序中绑定的引脚要和连接的引脚相同 ...

  9. ios开发之--为父view上的子view添加阴影

    项目中碰到一个问题,在tableview的headerview里面有很一个子view,设计师的要求是在下方添加一个阴影,效果如下: 以前的实现思路就是,代码如下: 添加阴影 调用视图的 layer C ...

  10. git合并单个节点

    有两个分支 # git branch -a * branchA branchB A分支合并B分支单个节点 # git log commit 6b4f9e1e1a1e1ed3e7ca3a1f15ce1f ...