题解 | JAVA #合并区间# [P0-T2]

合并区间

http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a

import java.util.*;
 
public class Solution {
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
      if (intervals.size() <= 1) return intervals;
       
      Collections.sort(intervals, (a,b)->a.start - b.start);
      ArrayList<Interval> ans = new ArrayList<>();
      ans.add(intervals.get(0));
       
      for (int i = 1; i < intervals.size(); i++) {
        Interval prev = ans.get(ans.size()-1);
        Interval cur = intervals.get(i);
         
        if (cur.start <= prev.end)  // prev intersects cur, merge
          prev.end = Math.max(cur.end, prev.end);
        else  // disjunct, add cur to ans
          ans.add(cur);
      }
      return ans;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务