标签:
Merge Intervals
问题:
Given a collection of intervals, merge all overlapping intervals.
思路:
不排序 直接上根据交集的特性
排序后再判断
简单的数学推导
我的代码1:
public class Solution { public List<Interval> merge(List<Interval> intervals) { if(intervals == null || intervals.size() == 0) return intervals; for(int i = 0; i < intervals.size(); i++) { Interval interval = intervals.get(i); int min = interval.start; int max = interval.end; for(int j = i+1; j < intervals.size(); j++) { Interval tmp = intervals.get(j); if(isIntersect(interval, tmp)) { intervals.remove(j); j--; max = Math.max(max, tmp.end); min = Math.min(min, tmp.start); } } if(min == interval.start && max == interval.end) i++; interval.start = min; interval.end = max; i--; } return intervals; } public boolean isIntersect(Interval one, Interval two) { int oneS = one.start; int oneE = one.end; int twoS = two.start; int twoE = two.end; if(oneE >= twoS && oneE <= twoE) return true; if(twoE >= oneS && twoE <= oneE) return true; if(oneE >= twoE && oneS <= twoS) return true; if(twoE >= oneE && twoS <= oneS) return true; return false; } }
我的代码2:
public class Solution { public List<Interval> merge(List<Interval> intervals) { if(intervals == null || intervals.size() == 0) return intervals; Collections.sort(intervals, new IntervalComparator()); for(int i = 0; i < intervals.size() - 1; i++) { Interval one = intervals.get(i); Interval two = intervals.get(i+1); if(one.end >= two.start) { one.end = Math.max(one.end, two.end); intervals.remove(i+1); i--; } } return intervals; } private class IntervalComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { return a.start - b.start; } } }
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4340345.html