LeetCode: 56. Merge Intervals(Medium)
阿新 • • 發佈:2018-01-26
oid highlight ava port ger println mage str .get
1. 原題鏈接
https://leetcode.com/problems/merge-intervals/description/
2. 題目要求
給定一個Interval對象集合,然後對重疊的區域進行合並。Interval定義如下
例如下圖中,[1, 3] 和 [2, 6]是有重疊部分的,可以合並成[1, 6]
3. 解題思路
先取第一個interval對象的 start 和 end 的值 ,然後對這個集合進行遍歷。比較當前遍歷對象的start是否比前一個對象的end小,小的話則說明二者存在覆蓋,然後對二者進行合並
4. 代碼實現
import java.util.LinkedList; import java.util.List; public class MergeIntervals56 { public static void main(String[] args) { Interval in1 = new Interval(1, 3); Interval in2 = new Interval(2, 6); Interval in3 = new Interval(8, 10); Interval in4 = new Interval(15, 18); List<Interval> ls = new LinkedList<Interval>(); ls.add(in1); ls.add(in2); ls.add(in3); ls.add(in4); for (Interval in : merge(ls)) System.out.println(in.start + " " + in.end); } public static List<Interval> merge(List<Interval> intervals) { if (intervals.size() <= 1) return intervals; List<Interval> res = new LinkedList<Interval>(); intervals.sort((i1, i2) -> Integer.compare(i1.start, i2.start)); int start = intervals.get(0).start; int end = intervals.get(0).end; for (Interval in : intervals) { if (in.start <= end) { end = Math.max(in.end, end); } else { res.add(new Interval(start, end)); start = in.start; end = in.end; } } res.add(new Interval(start, end)); return res; } } class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } }
LeetCode: 56. Merge Intervals(Medium)