【线段树】【leetcode 729. 我的日程安排表 I】

发布时间 2023-07-11 16:33:38作者: fishcanfly
class MyCalendar {
    class Seg {
        int l;
        int r;
        boolean val;
        Seg left;
        Seg right;

        public Seg(int x, int y) {
            this.l = x;
            this.r = y;
            this.val = false;
            this.left = null;
            this.right = null;
        }

        public boolean exist(int left, int right) {
            if(this.val){
                return true;
            }
            int mid = (this.l + this.r) / 2;

            if (left > mid) {
                if (this.right != null) {
                    return this.right.exist(left, right);
                }
                return false;
            } else if (right <= mid) {
                if (this.left != null) {
                    return this.left.exist(left, right);
                }
                return false;
            } else {
                boolean exist = false;
                if (this.left != null) {
                    exist = this.left.exist(left, mid);
                }
                if (this.right != null) {
                    exist = exist | this.right.exist(mid + 1, right);
                }
                return exist;
            }
        }

        public void insert(int start, int end) {
            if (start <= this.l && this.r <= end) {
                this.val = true;
                return;
            }
            int mid = (this.l + this.r) / 2;
            if (start > mid) {
                if (this.right == null) {
                    this.right = new Seg(mid + 1, this.r);
                }
                this.right.insert(start, end);
            } else if (end <= mid) {
                if (this.left == null) {
                    this.left = new Seg(this.l, mid);
                }
                this.left.insert(start, end);
            } else {
                if (this.right == null) {
                    this.right = new Seg(mid + 1, this.r);
                }
                if (this.left == null) {
                    this.left = new Seg(this.l, mid);
                }
                this.right.insert(mid + 1, end);
                this.left.insert(start, mid);
            }
        }
    }

    Seg root = null;

    public MyCalendar() {
        root = new Seg(0, 1000_000_000);
    }

    public boolean book(int start, int end) {
        if (root.exist(start, end-1)) {
            return false;
        }
        root.insert(start, end-1);
        return true;
    }

    public static void main(String[] args) {
        MyCalendar calendar = new MyCalendar();
        System.out.println(calendar.book(47,50));
        System.out.println(calendar.book(15,25));
        System.out.println(calendar.book(20,30));
    }
}

/**
 * Your MyCalendar object will be instantiated and called as such:
 * MyCalendar obj = new MyCalendar();
 * boolean param_1 = obj.book(start,end);
 */