模擬面試隊列:原有 N 人編號序列,Mr.true 拿到編號 P,插入第 Q 個位置 (1-based)。輸出新序列。
a[0..N-1]pos = Q-1 (0-based)for(i=N; i>pos; i--) a[i] = a[i-1]a[pos] = Pa[0..N] (新長度 N+1)#include <stdio.h>
int main() {
int T, N, P, Q, a[10001];
scanf("%d", &T);
while (T--) {
scanf("%d", &N);
for (int i = 0; i < N; i++) scanf("%d", &a[i]);
scanf("%d %d", &P, &Q);
int pos = Q - 1;
for (int i = N; i > pos; i--) a[i] = a[i-1];
a[pos] = P;
for (int i = 0; i <= N; i++) {
printf("%d", a[i]);
if (i < N) printf(" ");
}
if (T) printf("\n");
}
return 0;
}
t,k 嘗試原地輪轉,邏輯錯誤且難懂輸入: N=3, 序列=1 2 3, P=4, Q=2 pos=1 搬移: a[3]=a[2]=3, a[2]=a[1]=2 插入: a[1]=4 結果: 1 4 2 3 ✓
| 時間 | 空間 |
|---|---|
| O(N) 每測資 | O(N) 陣列 |