1 条题解
-
0
方法思路
- 题目要求按照用户第一次浏览的顺序输出用户ID
- 使用哈希集合(HashSet)来快速判断用户ID是否已经出现过
- 关键优化点:使用更高效的I/O处理方式,如BufferedReader和PrintWriter,避免Scanner的性能问题
- 对于每个用户ID,立即判断并输出,无需存储所有结果再输出
- 这样可以减少内存使用并提高处理速度
代码实现
Java
import java.io.*; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = Integer.parseInt(br.readLine()); Set<String> seen = new HashSet<>(); for (int i = 0; i < n; i++) { String userId = br.readLine(); if (!seen.contains(userId)) { seen.add(userId); out.println(userId); } } out.flush(); out.close(); br.close(); } }
Python
import sys def process_records(): n = int(sys.stdin.readline().strip()) seen = set() for _ in range(n): user_id = sys.stdin.readline().strip() if user_id not in seen: seen.add(user_id) print(user_id) # 执行处理 process_records()
C++
#include <iostream> #include <unordered_set> #include <string> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; cin.ignore(); // 消耗换行符 unordered_set<string> seen; seen.reserve(n); // 预分配空间 string userId; for (int i = 0; i < n; i++) { getline(cin, userId); if (seen.find(userId) == seen.end()) { seen.insert(userId); cout << userId << '\n'; // 使用'\n'代替endl避免刷新 } } cout.flush(); // 最后一次性刷新输出缓冲区 return 0; }
- 1
信息
- ID
- 43
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 4
- 已通过
- 1
- 上传者