Interview Questions

56. Merge Intervals

2016-03-22  本文已影响94人  宋翰要长肉

Algorithm

Complexity

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<Interval> merge(List<Interval> intervals) {
        if (intervals == null || intervals.size() == 0) {
            return intervals;
        }
        Collections.sort(intervals, new Comparator<Interval>() {
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }            
        });
        int size = intervals.size();
        List<Interval> 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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读