Merge two sorted (ascending) lists of interval and return it as a new sorted list. The new sorted list should be made by splicing together the intervals of the two lists and sorted in ascending order.
Example
Example1
Input: list1 = [(1,2),(3,4)] and list2 = [(2,3),(5,6)]
Output: [(1,4),(5,6)]
Explanation:
(1,2),(2,3),(3,4) --> (1,4)
(5,6) --> (5,6)
Example2
Input: list1 = [(1,2),(3,4)] and list2 = [(4,5),(6,7)]
Output: [(1,2),(3,5),(6,7)]
Explanation:
(1,2) --> (1,2)
(3,4),(4,5) --> (3,5)
(6,7) --> (6,7)
Notice
- The intervals in the given list do not overlap.
- The intervals in different lists may overlap.
思路:先merge成一个list,然后转换成我熟悉的,merge 一个list
/**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
* }
*/
public class Solution {
/**
* @param list1: one of the given list
* @param list2: another list
* @return: the new sorted list of interval
*/
public List<Interval> mergeTwoInterval(List<Interval> list1, List<Interval> list2) {
List<Interval> list = new ArrayList<Interval>();
if(list1 == null || list1.size() == 0) return list2;
if(list2 == null || list2.size() == 0) return list1;
List<Interval> templist = new ArrayList<Interval>();
int i = 0; int j = 0;
while(i < list1.size() && j < list2.size()){
Interval a = list1.get(i);
Interval b = list2.get(j);
if(a.start < b.start){
templist.add(a);
i++;
} else {
templist.add(b);
j++;
}
}
while(i < list1.size()){
templist.add(list1.get(i));
i++;
}
while(j < list2.size()){
templist.add(list2.get(j));
j++;
}
return mergeInterveral(templist);
}
private List<Interval> mergeInterveral(List<Interval> list) {
List<Interval> res = new ArrayList<Interval>();
Interval cur = list.get(0);
for(int i = 1; i < list.size(); i++){
Interval next = list.get(i);
if(cur.end >= next.start){
cur = new Interval(cur.start, Math.max(cur.end, next.end));
} else {
// cur.end < next.start;
res.add(cur);
cur = next;
}
}
res.add(cur);
return res;
}
}