Rotate Array
题目连接:https://oj.leetcode.com/problems/rotate-array/
Runtimes:26ms
1、问题
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.
2、分析
最传统的想法当然是用O(n)的空间,按照第i个数放在(i+k)%n的位置上来操作。但是题目要求是只用O(1)的空间,那么想到可以用逆序的操作,首先进行一次全范围逆序,然后再分别在0~(k-1),k~(n-1)的范围内进行逆序,最终得到解。
3、小结
整个过程需要三次逆序,时间复杂度为O(n),逆序时只消耗O(1)的空间。
4、实现
class Solution {
public:
void reverse(int nums[], int sta, int end)
{
for(int i = sta, j = end; i < j; i++, j--)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
void rotate(int nums[], int n, int k) {
k = k % n;
if(k == 0)
return;
reverse(nums, 0, n - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, n - 1);
}
};
5、三思
这道题比较简单,话说题目要求弄至少三种解法,容我三思一下哈。
参考链接:http://leetcode.com/2010/04/rotating-array-in-place.html