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.
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
#include<iostream>
using namespace std;
class Solution {
public:
void rotate(int nums[], int n, int k) /* solution one */
{ //时间复杂度为O(k*n);空间复杂度O(1)
int temp;
for (int i = 0; i < k; i++)
{
temp = nums[n - 1];
for (int j = n - 2; j >= 0; j--)
{
nums[j+1] = nums[j];
}
nums[0] = temp;
}
}
void rotate2(int nums[], int n, int k) /* solution two */
{
k = k%n;
int *temp = new int[n];
memcpy(temp, nums + n - k, sizeof(int)*k);
memcpy(temp+k,nums,sizeof(int)*(n-k));
memcpy(nums, temp, sizeof(int)*n);
delete[] temp;
/*
void *memcpy(void *dest, const void *src, size_t n);
c和c++使用的内存拷贝函数,memcpy函数的功能是从源src所指的内存地址的起始位置开始
拷贝n个字节到目标dest所指的内存地址的起始位置中。
注意:dest和src在内存的位置,可能会产生覆盖的情况。
*/
}
void reverse(int nums[], int start, int end)
{
int i = 0;
while (start < end)
{
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
start++;
end--;
}
}
void rotateArray3(int nums[],int n, int k)
{ //最优效率的方法,时间复杂度为O(n);空间复杂度为O(1)
reverse(nums, 0, n - k-1 );
reverse(nums, n - k, n-1);
reverse(nums, 0, n - 1);
}