/**
* 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 {
public List<Interval> merge(List<Interval> intervals) {
List<Integer> list = new ArrayList<>();
List<Interval> result = new ArrayList<>();
if(intervals.size() == 0){
return result;
}
HashMap<Integer, Interval> map = new HashMap<>();
for(int i = 0; i < intervals.size(); i++){
Interval interval = intervals.get(i);
if(!map.containsKey(interval.start)){
list.add(interval.start);
map.put(interval.start, interval);
} else {
Interval lastInterval = map.get(interval.start);
int end = Math.max(lastInterval.end, interval.end);
interval = new Interval(lastInterval.start, end);
map.put(interval.start, interval);
}
}
Collections.sort(list);
for(int i = 0 ; i < list.size()-1;i++){
Interval interval = map.get(list.get(i));
if(interval.end >= list.get(i+1)){
Interval next = map.get(list.get(i+1));
Interval mergedInterval = new Interval(interval.start, Math.max(interval.end, next.end));
map.put(list.get(i+1), mergedInterval);
} else {
result.add(interval);
}
}
result.add(map.get(list.get(list.size()-1)));
return result;
}
}
网友评论