日期:2025年9月23日
ZeroJudge 題目連結:e447. queue 練習
解題想法
這題就是考 queue 的操作,在 Python 要引入 collections 函式庫的 deque,在 C++ 要引入 queue 或是 deque 都可以。
Python 程式碼
使用時間約為 0.5 s,記憶體約為 6.6 MB,通過測試。
from collections import deque
n = int(input())
arr = deque()
for _ in range(n):
line = list(map(int, input().split()))
if len(line) == 1:
if line[0] == 2:
if arr: print(arr[0])
else: print(-1)
elif line[0] == 3 and arr: arr.popleft()
else:
arr.append(line[1])
C++ 程式碼
使用時間約為 24 ms,記憶體約為 600 kB,通過測試。
#include <cstdio>
#include <deque>
using namespace std;
int main() {
int n; scanf("%d", &n);
deque<int> arr;
for(int i=0; i<n; i++) {
int k; scanf("%d", &k);
if (k == 1) {
int x; scanf("%d", &x);
arr.push_back(x);
} else if (k == 2) {
if (!arr.empty()) printf("%d\n", arr.front());
else printf("-1\n");
} else if (k == 3 && !arr.empty()) {
arr.pop_front();
}
}
return 0;
}
沒有留言:
張貼留言