任务是将数组的子数组向左或向右旋转给定次数。
让我用一个例子来解释这一点:
数据 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
如果 begin = 3 且 end = 7,则子数组为 {0, 1, 2,3、4、5、6、7、 8, 9};
如果 begin = 7 且 end = 3,则子数组为 {0, 1, 2, 3, 4, 5, 6,7, 8, 9};
如果 begin = 3 且 end = 7,则结果为 {0, 1, 2,6、7、3、4、5、 8, 9};
如果 begin = 7 且 end = 3,则结果为 {8, 9, 0, 1,, 4, 5, 6,2, 3, 7};
我已经编写了执行此任务的代码,但速度很慢。
有人可以给我提示如何让它更快吗?
重要提示:除了数据、子程序和内置函数之外,我不允许使用其他数组。
#include <iostream>
using namespace std;
int main(){
int dataLength;
cin >> dataLength;
int data [ dataLength ];
for (int i = 0; i < dataLength; i++){
cin >> data [ i ];
}
int begin;
int end;
int rotation;
int forLoopLength;
int tempBefore;
int tempAfter;
cin >> begin;
cin >> end;
cin >> rotation;
if (end > begin)
forLoopLength = (end - begin) + 1;
else
forLoopLength = (end - begin) + 1 + dataLength;
if (rotation < 0)
rotation = forLoopLength + (rotation % forLoopLength);
else
rotation = rotation % forLoopLength;
for (int i = 0; i < rotation; i++) {
tempBefore = data [ end ];
for (int i = 0; i < forLoopLength; i++) {
tempAfter = data [ (begin + i) % dataLength ];
data [ (begin + i) % dataLength ] = tempBefore;
tempBefore = tempAfter;
}
}
for (int i = 0; i < dataLength; i ++ ) {
cout << data [ i ] << " ";
}
return 0;
}