2014年11月30日星期日

[Leetcode] Merge Interval

Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

Write a comparator to sort the intervals according to their start time. Then from the first interval, we do following:
  1. initialize the current merged interval using the first interval
  2. if the current interval intersect with the current merged interval, then we update the endTime of the current interval
  3. otherwise we insert the current merged interval to the result, and update the current merged interval using the current interval
In all case, their would not have the situation where current interval's start time is lower than current merged interval's start time, since we have sort the list according to the start time. Be careful with the final state, the last merged interval is not added to the result yet when the for loop terminate.

    public class myComparator implements Comparator<Interval> {
        public int compare(Interval i1, Interval i2) {
            return i1.start - i2.start;
        }
    }
    public List<Interval> merge(List<Interval> intervals) {
        if(intervals.size() == 0)
            return intervals;
        List<Interval> res = new ArrayList<Interval>();
        Collections.sort(intervals, new myComparator());
        int startTime = intervals.get(0).start, endTime = intervals.get(0).end;
        for(Interval i : intervals) {
            if(i.start > endTime) {
                Interval interval = new Interval(startTime, endTime);
                res.add(interval);
                startTime = i.start;
                endTime = i.end;
            }
            else {
                endTime = Math.max(endTime, i.end);
            }
        }
        Interval interval = new Interval(startTime, endTime);
        res.add(interval);
        return res;
    }

没有评论:

发表评论