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