一行N个位置,两种操作。
seat: 每次每个同学坐在一个位置,要满足尽量离最近的同学最远,
leave(i), 第i个位置的人起来,保证第i的位置是有人的
sol:
将相邻的两个人化为一个区间,那么每次seat的位置,就是最远的区间的中点。需要处理边界问题,我们可以虚拟出-1和N两个点,初始化的时候插入(-1, N)这个区间,注意怎么计算区间的distance的。
至于怎么取出最大的distance的,可以使用优先队列来实现
时间复杂度:
seat: O(lgN)
leave: O(N)
public class ExamRoom {
int N;
PriorityQueue<Interval> pq;
public ExamRoom(int N) {
this.N = N;
this.pq = new PriorityQueue<>((o1, o2) -> {
if (o1.d != o2.d) return Integer.compare(o2.d, o1.d);
return Integer.compare(o1.x, o2.x);
});
pq.add(new Interval(-1, N));
}
public int seat() {
int s;
Interval poll = pq.poll();
if (poll.x == -1) s = 0;
else if (poll.y == N) s = N - 1;
else s = (poll.x + poll.y) / 2;
pq.add(new Interval(poll.x, s));
pq.add(new Interval(s, poll.y));
return s;
}
public void leave(int p) {
Interval s, e;
s = e = null;
ArrayList<Interval> intervals = new ArrayList<>(pq);
for (Interval interval : intervals) {
if (interval.y == p) s = interval;
if (interval.x == p) e = interval;
if (s != null && e != null) break;
}
pq.remove(s);
pq.remove(e);
pq.add(new Interval(s.x, e.y));
}
class Interval {
int x, y, d;
public Interval(int x, int y) {
this.x = x;
this.y = y;
if (x == -1) d = y;
else if (y == N) d = N - 1 - x;
else d = (y - x) / 2;
}
}
}