Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

Java solution with custom Comparator

0 votes
103 views

Basically just sort the list by start, if start is the same, sort by end, in ascending order. Then compare start and end values for each pair next to each other.

public class Solution {
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if(intervals == null) return null;
    if(intervals.size() == 1 || intervals.size() == 0) return intervals;
    ArrayList<Interval> list = new ArrayList<Interval>();
    Collections.sort(intervals, new IntervalCompare());
    int astart = intervals.get(0).start, aend = intervals.get(0).end;
    int i = 1;
    while(i < intervals.size()){
        int bstart = intervals.get(i).start, bend = intervals.get(i).end;
        if(aend < bstart){
            list.add(new Interval(astart, aend));
            astart = bstart;
            aend = bend;
        }
        else if(aend == bstart){
            aend = bend;
        }
        else if(aend < bend){
                aend = bend;
        }
        i++;
    }
    list.add(new Interval(astart, aend));
    return list;
}

}

class IntervalCompare implements Comparator{

@Override
public int compare(Interval a, Interval b){
    if(a.start < b.start) return -1;
    else if(a.start == b.start){
        if(a.end < b.end) return -1;
        else return 1;
    }
    else return 1;
}

}

I wonder if anyone is using a segment tree/interval tree solution. I really want to see if this problem can be applied to a tree structure.

asked Dec 13, 2013 in Merge Intervals by zchen (460 points)

Could you please update your code format correctly, since the last } is out of box? Select all code, then click {} button.

I just don't see the point of using an interval tree. The running time will likely be O(n log n) as for your solution, but it will worse in term of space complexity as you need to build the tree.

Please log in or register to answer this question.


...