Algorithm-merge interval

Algorithm-merge interval

Algorithm-merge interval

This question is also quite interesting.
LeetCode (LeetCode56)

给出一个区间的集合,请合并所有重叠的区间。

示例 1:

输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:

输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。

The idea is very clear, the trilogy:

1. Sort to ensure that the starting position of the previous interval in the two-dimensional array is always less than or equal to the starting position of the
latter interval 2. When the starting position of the latter interval is greater than the end position of the previous interval, we add a new interval
3. If this condition is not met, we need to merge the intervals. The merged interval may be the end of the previous interval or the end of the latter interval. The specific need to compare

    public int[][] merge(int[][] intervals) {
    
    
    	//排序,确保二维数组中前一个区间的起始位置总是小于或等于后一个区间的起始位置
        Arrays.sort(intervals,(o1,o2)->o1[0]-o2[0]);
        ArrayList<int[]> list=new ArrayList<>();
        for(int i=0;i<intervals.length;i++){
    
    
        	//满足后一个区间的起始位置大于前一个区间的结束位置,我们添加新区间
            if(list.size()==0||list.get(list.size()-1)[1]<intervals[i][0]){
    
    
                list.add(intervals[i]);
            }else{
    
    //不满足此条件的话我们需要合并区间,合并后的区间可能是前一个区间的末尾也可能是后一个区间的末尾,具体需要比较
                list.get(list.size()-1)[1]=Math.max(intervals[i][1],list.get(list.size()-1)[1]);
            }
        }
        //转化成二维数组
        return list.toArray(new int[list.size()][2]);
    }

Guess you like

Origin blog.csdn.net/qq_23594799/article/details/105329818