Merge Overlapping Intervals

前端 未结 5 737
深忆病人
深忆病人 2021-02-04 10:48

Question : Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals. Let th

5条回答
  •  耶瑟儿~
    2021-02-04 11:33

    My implementation using BST. O(logn) to merge: Inorder traversal gives you updated intervals.

    private static Interval add(Interval root, Interval x){
        if(root == null)
            return x;
        if(root.start >= x.start){
            root.left = add(root.left,x);
            if(mergeLeft(root,root.left)){
                root.left = null;
            }               
        }
        else{
            root.right = add(root.right,x);
            if(mergeRight(root,root.right)){
                root.right = null;
            }
        }
    
        return root;
    }
    
    private static boolean mergeLeft(Interval root,Interval left){
        if(left.end < root.start)
            return false;
    
        else{
            root.start = Math.min(root.start, left.start);
            root.end = Math.max(root.end, left.end);
            return true;
        }
    }
    
    private static boolean mergeRight(Interval root,Interval right){
        if(right.start > root.end)
            return false;
        else{
            root.start = Math.min(root.start, right.start);
            root.end = Math.max(root.end, right.end);
            return true;
        }
    }
    

提交回复
热议问题