标签:medium math tor crt tco over class span cti
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]
.
先写comparator按照interval的开始时间出现早晚排好序。接着开始遍历每个interval,如果和上一个有交叉(crt.start <= prev.end),那就改上一个的end为更持久的一个,如果和上一个没有交叉,那就把之前记录的间隔推入结果中,重新开始新的检查。
1.O(n)空间:
/** * 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 { private Comparator<Interval> comparator = new Comparator<Interval>(){ public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } }; public List<Interval> merge(List<Interval> intervals) { List<Interval> result = new ArrayList<Interval>(); if (intervals == null || intervals.size() == 0) { return result; } Collections.sort(intervals, comparator); int start = intervals.get(0).start; int end = intervals.get(0).end; for (int i = 1; i < intervals.size(); i++) { Interval crt = intervals.get(i); if (crt.start <= end) { end = Math.max(end, crt.end); } else { result.add(new Interval(start, end)); start = crt.start; end = crt.end; } } result.add(new Interval(start, end)); return result; } }
2.O(1)空间,原地合并
/** * 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 { private Comparator<Interval> comparator = new Comparator<Interval>(){ public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } }; public List<Interval> merge(List<Interval> intervals) { List<Interval> result = new ArrayList<Interval>(); if (intervals == null || intervals.size() == 0) { return result; } Collections.sort(intervals, comparator); Interval last = intervals.get(0); for (int i = 1; i < intervals.size(); i++) { Interval crt = intervals.get(i); if (crt.start <= last.end) { last.end = Math.max(last.end, crt.end); } else { result.add(last); last = crt; } } result.add(last); return result; } }
leetcode56- Merge Intervals- medium
标签:medium math tor crt tco over class span cti
原文地址:http://www.cnblogs.com/jasminemzy/p/7820938.html