Clean TreeSet solution in Java


  • 0
    T
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            
            TreeSet<Interval> tree = new TreeSet<Interval>(new Comparator<Interval>() {
                @Override
                public int compare(Interval i1, Interval i2) {
                    if (i1.end < i2.start) return -1;
                    else if (i1.start > i2.end) return 1;
                    else return 0;
                }
            });
            
            for (Interval i: intervals) {
                while (tree.contains(i)) {
                    Interval x = tree.ceiling(i);
                    tree.remove(x);
                    i = new Interval(Math.min(i.start, x.start), Math.max(i.end, x.end));
                }
                tree.add(i);
            }
            
            return new ArrayList<Interval>(tree);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.