[leetcode]Merge Intervals
Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
For example,
Given[1,3],[2,6],[8,10],[15,18]
,
return[1,6],[8,10],[15,18]
.
算法思路:
将intervals按照start进行排序,然后建立一个空的list,把intervals的元素逐个插入并做合并操作。
值得注意的是:如果intervals的待插入元素能与list的元素合并,则一定是与最后一个合并。think about it
【吐槽】:这是第一遍时候想到的算法,还是很不错的,单次遍历,只不过当时不会用Collections.sort()自己手动的排序了。o(╯□╰)o
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * Interval() { start = 0; end = 0; } 7 * Interval(int s, int e) { start = s; end = e; } 8 * } 9 */ 10 public class Solution { 11 List<Interval> res = new ArrayList<Interval>(); 12 public List<Interval> merge(List<Interval> intervals) { 13 if(intervals == null || intervals.size() == 0) return res; 14 Collections.sort(intervals, new Comparator<Interval>(){ 15 public int compare(Interval a,Interval b){ 16 return a.start - b.start; 17 } 18 }); 19 List<Interval> list = new ArrayList<Interval>(); 20 list.add(intervals.get(0)); 21 for(int i = 1; i < intervals.size(); i++){ 22 Interval last = list.get(list.size() - 1); 23 Interval thus = intervals.get(i); 24 if(thus.start <= last.end){ 25 last.end = thus.end > last.end ? thus.end : last.end; 26 }else{ 27 list.add(thus); 28 } 29 } 30 return list; 31 } 32 }