Leetcode 855

一行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;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值