左旋转:把数组前若干数移动到尾部,如把字符串abcdef左旋转2位得到cdefab。右旋转则相反。
自己想的,时间复杂度O(n)。例子:
#include<iostream>
using namespace std;
template<typename T>
void LeftShift(T *p, int len, int k) {
if(k%len == 0)return ;
k %= len;
bool changed = false;
if(k > len/2) {
k = len - k;
changed = true;
}
T *q, *t;
t = p;
q = p + len - k;
for(int i = 0; i < k; i++) {
T temp = *t;
*t = *q;
*q = temp;
t++;
q++;
}
if(changed)LeftShift(p + k, len - k,len-2*k);
else LeftShift(p, len - k, k);
}
template<typename T>
void RightShift(T *p, int len, int k) {
LeftShift(p, len, len - k);
}
int main() {
char a[] = {'1','2','3','4','5','6','7'};
int len = 7;
for(int i = 0; i < len; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
LeftShift(a,len, 3);
for(int i = 0; i < len; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
《编程之美》:
转置3次
1 2 3 4 5 6
左旋转2(右旋转4)
左边两个1 2转置
右边四个3 4 5 6转置
成2 1 6 5 4 3
再转置总的
成3 4 5 6 1 2
时间复杂度O(n)
#include<iostream>
using namespace std;
template<typename T>
void Reserve(T *array, int beg, int end) {
for(; beg < end; beg++, end--) {
T temp = array[beg];
array[beg] = array[end];
array[end] = temp;
}
}
template<typename T>
void LeftShift(T *p, int len, int k) {
k%=len;
Reserve(p, 0, k - 1);
Reserve(p, k, len -1);
Reserve(p, 0, len -1);
}
template<typename T>
void RightShift(T *p, int len, int k) {
LeftShift(p, len, len - k);
}
int main() {
char a[] = {'a','b','1','2','3','4'};
int len = 6;
for(int i = 0; i < len; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
LeftShift(a,len, 1);
for(int i = 0; i < len; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}