循环移位的问题
1. 简述
设计一个算法,把一个含有N个元素的数组循环右移K位,要求时间复杂度为O(N),且只允许使用两个附加变量。
求解方法1:
void RightShift(char *arr, int N, int k)
{
k = k % K;
while(k--)
{
char t = arr[N-1];
for(int i = N-1; i > 0; i--)
arr[i] = arr[i-1];
arr[0] = t;
}
}
求解方法2:
#include <stdio.h>
#define N 10
void Loop_Shifting(int a[], int n, int k);
void Reverse(int a[], int low, int high);
void PrintNode(int a[], int n);
int main()
{
int a[N] = {1,2,3,4,5,6,7,8,9,0};
int n = 0;
int k = 0;
n = N;
k = 4;
PrintNode(a, n);
Loop_Shifting(a, n, k);
PrintNode(a, n);
return 0;
}
void Reverse(int a[], int low, int high)
{
int tmp = 0;
for(; low < high; low++, high--)
{
tmp = a[high];
a[high] = a[low];
a[low] = tmp;
}
}
void Loop_Shifting(int a[], int n, int k)
{
k = k % N;
Reverse(a, 0, (n - k - 1));
Reverse(a, (n - k), (n - 1));
Reverse(a, 0, (n - 1));
}
void PrintNode(int a[], int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%d", a[i]);
}
printf("\n");
}