LeetCode:56. Merge Intervals(合併區間)
阿新 • • 發佈:2018-12-21
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
方法1:
/** * 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; } * } */ class Solution { private class IntervalComparator implements Comparator<Interval> { @Override public int compare(Interval a, Interval b) { //return a.start < b.start ? -1 : a.start == b.start ? 0 : 1; if(a.start<b.start){ return -1; }else{ if(a.start==b.start){ return 0; }else{ return 1; } } } } public List<Interval> merge(List<Interval> intervals) { Collections.sort(intervals, new IntervalComparator()); for(Interval interval:intervals){ System.out.println(interval.start+"--"+interval.end); } LinkedList<Interval> merged = new LinkedList<Interval>(); for (Interval interval : intervals) { // if the list of merged intervals is empty or if the current // interval does not overlap with the previous, simply append it. if (merged.isEmpty() || merged.getLast().end < interval.start) { merged.add(interval); } // otherwise, there is overlap, so we merge the current and previous // intervals. else { merged.getLast().end = Math.max(merged.getLast().end, interval.end); } } return merged; } }
時間複雜度:O(n.logn)
空間複雜度:O(n)