1 class Solution { 2 public int[][] merge(int[][] intervals) { 3 /* 4 思路:左区间排序,若intervals[i][0] >= intervals[i-1][1]; 则重叠 5 将重叠区间新建放入res数组里,没重叠则放入原数组 6 */ 7 List<int[]> res = new LinkedList<>(); 8 Arrays.sort(intervals, (a,b) -> Integer.compare(a[0], b[0])); 9 //initial start 是最小左边界 10 int start = intervals[0][0]; 11 int rightmostRightBound = intervals[0][1]; 12 for(int i = 1; i < intervals.length; i++) { 13 //如果左边界大于最大右边界 14 if(intervals[i][0] > rightmostRightBound) {//没重叠 15 //加入区间 并且更新start 16 res.add(new int[]{start, rightmostRightBound}); 17 start = intervals[i][0]; 18 rightmostRightBound = intervals[i][1]; 19 } else { 20 //更新最大右边界 21 rightmostRightBound = Math.max(rightmostRightBound, intervals[i][1]); 22 } 23 } 24 res.add(new int[]{start, rightmostRightBound}); 25 return res.toArray(new int[res.size()][]); 26 } 27 }
标签:leetcode56,java,int,res,合并,rightmostRightBound,start,intervals,new From: https://www.cnblogs.com/zuamagee/p/17300534.html