056.Merge Intervals Posted on 2017-09-13 | In LeetCode Solution 1: accepted 28ms 59%Time: O(2n)Space: O(n) 1234567891011121314151617181920212223242526272829303132333435class Solution { public List<Interval> merge(List<Interval> intervals) { if (intervals.size() < 2) return intervals; List<Interval> result = new ArrayList<>(); Collections.sort(intervals, new IntervalComparator()); Interval temp = new Interval(); for (int i = 0; i < intervals.size() - 1; i++) { if (intervals.get(i).end < intervals.get(i + 1).start) { result.add(intervals.get(i)); } else if (intervals.get(i).start == intervals.get(i + 1).start) { intervals.get(i + 1).end = Math.max(intervals.get(i).end, intervals.get(i + 1).end); } else { intervals.get(i + 1).start = intervals.get(i).start; intervals.get(i + 1).end = Math.max(intervals.get(i).end, intervals.get(i + 1).end); } } result.add(intervals.get(intervals.size() - 1)); return result; } private class IntervalComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { if (a.start < b.start) return -1; else if (a.start > b.start) return 1; else return 0; } } } Simplified123456789101112131415161718192021222324252627class Solution { public List<Interval> merge(List<Interval> intervals) { if (intervals.size() < 2) return intervals; List<Interval> result = new ArrayList<>(); Collections.sort(intervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); Interval temp = new Interval(); for (int i = 0; i < intervals.size() - 1; i++) { Interval current = intervals.get(i); Interval next = intervals.get(i + 1); if (current.end < next.start) { result.add(current); } else { next.start = current.start; next.end = Math.max(current.end, next.end); } } result.add(intervals.get(intervals.size() - 1)); return result; } }