为什么92%的AI监控系统在凌晨3点崩溃?:揭秘实时数据流断层的7个隐形杀手
2026/8/1 14:13:48
输入:
ExamRoom(int n),座位编号为[0, n-1]seat():安排下一位学生入座leave(int p):座位p的学生离开(保证p上有人)要求:
seat()必须选择离最近的人最远的位置;输出:
seat()返回座位编号;leave()无返回。思路:
用一个有序集合set<int> students维护当前已坐下的座位编号(自动有序)。
最优位置只可能出现在三类“空段”里:
0到第一个已坐位置first0,到最近人的距离就是first - 0 = firstdist = first,候选座位bestSeat = 0prev和s之间(s - prev) / 2students,对每一对相邻座位计算d = (s - prev) / 2d > dist,更新bestSeat = prev + dlast到n-1n-1,距离就是(n-1) - lasttailDist > dist,更新bestSeat = n-1最后把bestSeat插入集合并返回。
直接students.erase(p)即可。
复杂度:
seat():O(M) 扫描当前已坐人数M(set 遍历) + 插入 O(log M)leave():O(log M)classExamRoom{private:intN;set<int>students;public:ExamRoom(intn){N=n;}intseat(){if(students.empty()){students.insert(0);return0;}intdist=*students.begin();// 头部空段距离intbestSeat=0;intprev=-1;for(ints:students){if(prev!=-1){intd=(s-prev)/2;if(d>dist){dist=d;bestSeat=prev+d;}}prev=s;}inttailDist=(N-1)-*students.rbegin();if(tailDist>dist){bestSeat=N-1;}students.insert(bestSeat);returnbestSeat;}voidleave(intp){students.erase(p);}};