0 of 1 Questions completed
Questions:
You have already completed the quiz before. Hence you can not start it again.
Quiz is loading…
You must sign in or sign up to start the quiz.
You must first complete the following:
0 of 1 Questions answered correctly
Your time:
Time has elapsed
You have reached 0 of 0 point(s), (0)
Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)
1、完善程序: (序列重排) (2013年普及组)
全局数组变量 a 定义如下:
const int SIZE = 100;
int a[SIZE], n;
它记录着一个长度为n的序列 a1,a2,…,an。 现在需要一个函数,以整数p(1≤p≤n) 为参数,实现如下功能: 将序列a的前p个数与后n−p个数对调,且不改变这p个数(或n−p 个数)之间的相对位置。 例如,长度为5的序列 1,2,3,4,5,当 p=2时重排结果为3,4,5,1,2 。 有一种朴素的算法可以实现这一需求,其时间复杂度为 O(n)、空间复杂度为 O(n):
1 2 3 4 5 6 7 8 9 10 |
void swap1( int p ) { int i, j, b[SIZE]; for ( i = 1; i <= p; i++ ) b[①] = a[i]; // (3分) for ( i = p + 1; i <= n; i++ ) b[i - p] = ②; // (3分) for ( i = 1; i <= ③; i++ ) // (2分) a[i] = b[i]; } |
我们也可以用时间换空间,使用时间复杂度为 O(n^2 )、空间复杂度为O(1) 的算法:
1 2 3 4 5 6 7 8 9 10 11 |
void swap2( int p ) { int i, j, temp; for ( i = p + 1; i <= n; i++ ) { temp = a[i]; for ( j = i; j >= ④; j-- ) // ( 3 分) a[j] = a[j - 1]; ⑤ = temp; // ( 3 分) } } |
填空一:
填空二:
填空三:
填空四:
填空五: