56. Merge Intervals (Interval)
要先sort之后 判断a.end b.start才能找出interval
list可以用Collections.sort()进行排序
1 Collections.sort(intervals, new Comparator<Interval>(){ 2 @Override 3 public int compare(Interval a, Interval b) { 4 return a.start - b.start; 5 } 6 });
new Comparator<类型> 然后重写compare方法 返回数字就可以
1 class Solution { 2 public List<Interval> merge(List<Interval> intervals) { 3 ArrayList<Interval> res = new ArrayList<>(); 4 if(intervals.size() == 0) return intervals; 5 Collections.sort(intervals, new Comparator<Interval>(){ 6 @Override 7 public int compare(Interval a, Interval b) { 8 return a.start - b.start; 9 } 10 }); 11 12 res.add(intervals.get(0)); 13 for(int i = 1; i < intervals.size(); i++) { 14 if(res.get(res.size() - 1).end >= intervals.get(i).start) { 15 res.get(res.size() - 1).end = Math.max(res.get(res.size() - 1).end, intervals.get(i).end); 16 17 }else { 18 res.add(intervals.get(i)); 19 } 20 } 21 22 return res; 23 } 24 }