leetcode 原题链接: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.
提示:尽力提出多种方法解决这个问题,至少有三种方法可以解决。
简要分析:
1、根据题目的意思,最容易想到的做法就是每次都将数组的最后一位移动到数组的第一位,这样每次的移动次数为n,一共要循环k次,因此时间复杂度为O(n*k)。
2、根据July大神的思路,我们可以采用三次移动的方式来完成,其中用到的公式是(X'Y')' = YX。即首先将0~size-k-1进行首尾交换操作,然后将size-k~size-1进行首尾交换操作,最后将整个数组进行首尾交换操作。时间复杂度为O(2n) = O(n)
实现代码
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
void rotate(vector<int>& nums, int k)
{
if (nums.empty() || k == 0)
return;
if (k >= nums.size())
k %= nums.size();
if (k < nums.size())
k = k%nums.size();
rotate(nums, 0, nums.size() - k-1);
rotate(nums, nums.size() - k, nums.size()-1);
rotate(nums, 0, nums.size() - 1);
return;
}
void rotate(vector<int>& nums, int start, int end)
{
int temp = 0;
while (start < end)
{
temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
return;
}
void display(vector<int> nums)
{
for (vector<int>::iterator p = nums.begin(); p != nums.end(); p++)
{
cout << *p << " ";
}
cout << endl;
}
};
int main()
{
int nums[] = { 1, 2, 3, 4, 5, 6, 7 };
vector<int> intVector(nums, nums + 7);
Solution st;
st.rotate(intVector, -2);
st.display(intVector);
return 0;
}