56. 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].

sort的好处是，只用管end，不用管start, 因为新添加的Interval的start至少是大于等于结果集合里面已经添加的Interval的start的。换言之，start不受影响，简化了我们的处理。

/**
* 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 List<Interval> merge(List<Interval> intervals) {
ArrayList<Interval> res = new ArrayList<Interval>();
if (intervals == null || intervals.size() == 0) {
return intervals;
}
Comparator<Interval> comp = new Comparator<Interval>() {
public int compare(Interval t1, Interval t2) {
if (t1.start == t2.start) {
return t1.end - t2.end;
}
return t1.start - t2.start;
}
};
Collections.sort(intervals, comp);
for (int i=1; i<intervals.size(); i++) {
if (res.get(res.size()-1).end >= intervals.get(i).start) {
res.get(res.size()-1).end = Math.max(res.get(res.size()-1).end, intervals.get(i).end);
}
else {
}
}
return res;
}
}

/**
* 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 List<Interval> merge(List<Interval> intervals) {
List<Interval> ans = new ArrayList<>();
if (intervals == null || intervals.size() == 0) {
return ans;
}
Comparator<Interval> comp = new Comparator<Interval>(){
public int compare(Interval a, Interval b) {
return a.start == b.start ? a.end - b.end : a.start - b.start;
}
};
Comparator<Interval> cmp = new Comparator<Interval>(){
public int compare(Interval a, Interval b) {
return b.end - a.end;
}
};
Collections.sort(intervals, comp);
PriorityQueue<Interval> heap = new PriorityQueue<>(cmp);
for (int i = 1; i < intervals.size(); i++) {
if (heap.peek().end >= intervals.get(i).start) {
Interval cur = heap.poll();
Interval merge = new  Interval(cur.start, Math.max(cur.end, intervals.get(i).end));
} else {
}

}
while (!heap.isEmpty()) {
}
return ans;
}
}

56. Merge Intervals

(0)
(0)

0条