首页 > 代码库 > [leetcode] Merge Intervals
[leetcode] 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].
https://oj.leetcode.com/problems/merge-intervals/
思路:先按照起始点排序,然后遍历合并即可。
代码:
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;public class Solution { public ArrayList<Interval> merge(ArrayList<Interval> intervals) { if (intervals == null) return null; Collections.sort(intervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); ArrayList<Interval> res = new ArrayList<Interval>(); int i; for (i = 0; i < intervals.size();) { int j = i + 1; Interval merged = new Interval(intervals.get(i).start, intervals.get(i).end); while (j < intervals.size() && isConnected(merged, intervals.get(j))) { merged = merge(merged, intervals.get(j)); j++; } res.add(merged); i = j; } return res; } private boolean isConnected(Interval a, Interval b) { return (a.start >= b.start && a.start <= b.end) || (b.start >= a.start && b.start <= a.end); } private Interval merge(Interval a, Interval b) { int newStart = a.start < b.start ? a.start : b.start; int newEnd = a.end > b.end ? a.end : b.end; a.start = newStart; a.end = newEnd; return a; } public static void main(String[] args) { // [1,3],[2,6],[8,10],[15,18] Interval one = new Interval(2, 4); Interval two = new Interval(1, 2); Interval three = new Interval(4, 10); Interval four = new Interval(10, 18); ArrayList<Interval> intervals = new ArrayList<Interval>(); intervals.add(one); intervals.add(two); intervals.add(three); intervals.add(four); System.out.println(new Solution().merge(intervals)); }}
参考:
http://leetcodenotes.wordpress.com/2013/08/01/merge-intervals/
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。