The balance tree in Java

Source: Internet
Author: User

Leetcode 729

Given a bunch of segments, each segment has a starting point, an end point, with an array [(BEG1,END1), (Beg2,end2), (Beg3,end3) ...] To express. The following questions can be raised:

    • Whether these segments have coincident parts
    • What is the total length of these segments (coincident parts of multiple segments are counted only once), this problem is equivalent to the enhanced version of the above problem

If these segments are given at once, you can simply sort the segments by O (Nlog (n)) and then scan from left to right O (n) complexity.

This problem requires an on-line algorithm. Therefore, it is necessary to sort the start of each segment and, when inserting, determine whether the upper bound segment of start and the nether segment can accommodate the current segment. If implemented with an array, the complexity of O (N/2) is required for each insertion. If you use a balanced tree, the complexity of O (log (n)) is required for each insertion.

import Java.util.TreeMap;classMyCalendar {classNode {intStartintEnd Node (intStartintEnd) { This.Start= start; This.End= END; }}treemap<integer, node> a =NewTreemap<> (); Public MyCalendar() {A.put(-1,NewNode (-1,0)); A.put((int) (1e9+7),NewNode (int) (1e9+7), (int) (1e9+8)));} Public Boolean  Book(intStartintEnd) {Node floor = a.Floorentry(start).GetValue(); Node Ceil = A.Ceilingentry(start).GetValue();if(Start >= floor.)End&& End <= Ceil.Start) {A.put(Start,NewNode (start, end));return true; }Else{return false; }}}

The balance tree in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.