56. Merge Intervals

Algorithm

  • sort intervals according to start time in increasing order
  • traverse sorted intervals from first interval
    • if current interval is not the first interval and it overlaps the last interval in output list of intervals, merge these two intervals
      • update end time of last interval in output list of intervals to maximum of end times of the two intervals.
    • else add current interval into output list of intervals

Complexity

  • time complexity: O(NlgN)
    • time complexity of sorting: O(NlgN)
  • space complexity: O(N)
    • space used for output list of intervals

Code

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public List merge(List intervals) {
        if (intervals == null || intervals.size() == 0) {
            return intervals;
        }
        Collections.sort(intervals, new Comparator() {
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }            
        });
        int size = intervals.size();
        List result = new ArrayList();
        result.add(intervals.get(0));
        for (int i = 1; i < size; i++) {
            Interval first = result.get(result.size() - 1);
            Interval second = intervals.get(i);
             if (second.start > first.end) {
                result.add(second);
            } else {
                int newEnd = Math.max(first.end, second.end);
                first.end = newEnd;
            }
        }
        return result;
    }
}

你可能感兴趣的:(56. Merge Intervals)