方法1:
先把原数组拷贝一份,然后先将原数组的后k个拷贝,再将前numsSize-k个拷贝
void rotate(int* nums, int numsSize, int k) {
//可能存在k>numsSize的情况,先处理k
k = k % numsSize;
//拷贝数组
int arr[numsSize];
int i = 0;
int* ret = nums;
for (i = 0; i < numsSize; ++i)
{
arr[i] = *ret++;
}
//先拷贝后k个,再拷贝前numsSize-k个
int before = numsSize - k;
ret = nums;
for (i = before; i < numsSize; ++i)
{
*ret++ = arr[i];
}
for (i = 0; i < before; ++i)
{
*ret++ = arr[i];
}
}
方法2:
1️⃣前numsSize-k个元素倒置 :4 3 2 1 5 6 7
2️⃣后k个倒置:4 3 2 1 7 6 5
3️⃣整体倒置:5 6 7 1 2 3 4
void reverse(int* arr, int len)
{
int begin = 0;
int end = len - 1;
while (begin < end)
{
int tmp = arr[begin];
arr[begin] = arr[end];
arr[end] = tmp;
++begin;
--end;
}
}
void rotate(int* nums, int numsSize, int k)
{
if (k > numsSize)
{
k %= numsSize;
}
reverse(nums, numsSize - k);
reverse(nums + numsSize - k, k);
reverse(nums, numsSize);
}