标签:sort interval leetcode comparator
【题目】
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]
.
题意:有很多个区间,把有重叠的区间合并。
思路:先排序,然后检查相邻两个区间,看前一个区间的结尾是否大于后一个区间的开始,注意前一个区间包含后一个区间的情况。
用Java自带的sort()方法,只要自己重写compare()方法即可。
【Java代码】
/** * 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 class MyComparator implements Comparator<Interval> { @Override public int compare(Interval a, Interval b) { return a.start - b.start; } } public List<Interval> merge(List<Interval> intervals) { List<Interval> ans = new ArrayList<Interval>(); if (intervals.size() == 0) return ans; Collections.sort(intervals, new MyComparator()); int start = intervals.get(0).start; int end = intervals.get(0).end; for (int i = 0; i < intervals.size(); i++) { Interval inter = intervals.get(i); if (inter.start > end) { ans.add(new Interval(start, end)); start = inter.start; end = inter.end; } else { end = Math.max(end, inter.end); } } ans.add(new Interval(start, end)); return ans; } }
【LeetCode】Merge Intervals 解题报告
标签:sort interval leetcode comparator
原文地址:http://blog.csdn.net/ljiabin/article/details/44905385