LeetCode - Rotate Array
来源:互联网 发布:mac版chrome翻墙插件 编辑:程序博客网 时间:2024/06/03 07:48
https://leetcode.com/problems/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,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
这道题如果用extra space O(n)的话很简单,就是把第i个元素移动到 (i+k)%size 位置就行。但是如果只能用O(1) extra space的话,就是把一个元素移动到它对应的新位置,再把新位置的元素移动到下一个新位置,直到又回到初始位置为止。但这样的话,进行了一个圈,回到初始位置后,不一定是把数组中所有位置都移动了,而是看(size, k)的最大公约数,一共有gcd个圈,每个圈的起始位置是 0,1,2,... (gcd-1),但是这里没必要算出来gcd,只需要有一个counter变量,记录移了几个数了,一圈后,如果counter==size,说明移完了,如果counter<size,说明没移完,则把起始位置加1,继续移动新圈。这样的话,空间复杂度O(1),时间复杂度O(n)
代码如下:
public void rotate(int[] nums, int k) { int size = nums.length; int counter = 0; int start = 0; while(counter<size){ int last = start; int next = (start+k)%size; int val = nums[last]; do{ int tmp = nums[next]; nums[next] = val; val = tmp; last = next; next = (next+k)%size; counter++; }while(last!=start); start++; } }
0 0
- [leetcode][array] Rotate Array
- LeetCode[Array]: Rotate Image
- LeetCode:Rotate Array
- [LeetCode] Rotate Array
- *LeetCode-Rotate Array
- [LeetCode]189.Rotate Array
- Rotate Array - LeetCode - Java
- Rotate Array--Leetcode(Java)
- Leetcode--Rotate Array
- LeetCode: Rotate Array
- LeetCode Rotate Array
- Rotate Array(leetcode)
- leetcode Rotate Array
- Leetcode: Rotate Array
- [Leetcode]11 Rotate Array
- [LeetCode][189][Rotate Array]
- Leetcode:Rotate Array
- LeetCode: Rotate Array
- POJ lake counting(简单的dfs)
- tar.xz文件如何解压
- Android基础笔记(十二)- 使用AIDL来进行跨进程通信
- linx 线程切换的一些感悟
- 数据库作业一 姓名:肖波 学号:2013211527
- LeetCode - Rotate Array
- Google C++ 风格指南 - 中文版
- 求 2/1+3/2+5/3+8/5+13/8+…的前20项和
- Android FoldingLayout 折叠布局 原理及实现(二)
- hdoj 2120 Ice_cream's world I 【并查集判断成环数】
- 有序和无序数组的二分搜索算法+select第k小的元素
- TCP滑动窗口 - 动画演示
- css+div
- [NOI2011]兔农(斐波那契数列+乘法逆+矩阵加速)