标签:col .so com ret max exp over merge TE
First, sort the list, then merge from start to end.
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 considerred overlapping.
/** * 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 { public List<Interval> merge(List<Interval> intervals) { List<Interval> l = new LinkedList<Interval>(); if (intervals.size() == 0) return l; Collections.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { return o1.start - o2.start; } }); Interval in = intervals.remove(0); l.add(in); for (Interval i : intervals) { if (in.end >= i.start) { in.end = Math.max(in.end,i.end); } else { l.add(i); in = i; } } return l; } }
Merge Intervals--Collections排序
标签:col .so com ret max exp over merge TE
原文地址:https://www.cnblogs.com/liudebo/p/9251675.html