Leetcode problem solution 56-merge interval

Problem Description

The array intervals represents a collection of several intervals, and a single interval is intervals[i] = [starti, endi]. Please merge all overlapping intervals and return a non-overlapping interval array, which must cover all intervals in the input.

Example 1:

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

Example 2:

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

prompt:

1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104

Problem solving ideas

If we sort by the left end of the interval, then in the sorted list, the intervals that can be merged must be continuous. Or, we can consider that if the left end of the interval is not sorted, then for any two adjacent intervals, we have the following relationships. We
Insert picture description here
can see that there are 5 relationships between the two intervals. If we follow the left end of the interval For sorting, then there are only 3 relationships
Insert picture description here

In fact, relationship 1 and relationship 2 can be merged into an overlapping relationship, while relationship 3 is a non-overlapping relationship.
Here the interval set is represented by a two-dimensional array, so the question is, how to sort the two-dimensional array according to the specified conditions in Java?
The same is the compare method that needs to implement the Comparator interface. A comparator is passed in the Arrays.sort() function. The comparator uses an anonymous internal class to implement
the sample code for sorting two-dimensional arrays according to conditions in Java as follows :

public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int [][]matrix={
    
    {
    
    1,3},{
    
    6,8},{
    
    2,6},{
    
    4,7},{
    
    7,19},{
    
    12,18}};
		Arrays.sort(matrix,new Comparator<int[]>(){
    
    
			@Override
			public int compare(int[] o1, int[] o2) {
    
    
				return o1[0]-o2[0];
			}
		});
		for(int i=0;i<matrix.length;i++){
    
    
			System.out.println("x1="+matrix[i][0]+" x2="+matrix[i][1]);
		}
	}

Insert picture description here

We use dynamic array ArrayList collection lists to store the final answer.
First, we sort the intervals in the list in ascending order of the left end point.
Subsequently, the entire interval is scanned, and during the scanning process, we merge all the intervals that may have intersections.
We need to maintain a current interval each time, and before the loop, the first interval of the interval to be merged is used as the current interval:

  • If the left end of the interval selected when we scan is behind the right end of the current interval, then they will not overlap, we can add the current interval to the result set, and update the current interval to the interval selected during the scan;

  • Otherwise, they overlap. We need to compare the right endpoint value of the current interval with the right endpoint value of the interval selected during scanning, and set the right endpoint value of the current interval to the larger value of the two.

  • Insert picture description here

Implementation code

class Solution {
    
    
    public int[][] merge(int[][] intervals) {
    
    
        if(intervals.length==0 ||intervals.length==1){
    
    
            return intervals;
        }
        //对区间左端点进行排序
        Arrays.sort(intervals,new Comparator<int[]>(){
    
    
            public int compare(int []o1,int []o2){
    
    
                return o1[0]-o2[0];
            }
        });
        //创建动态数组用于保存最终结果集
        List<int[]> lists=new ArrayList<int[]>();
        int start=intervals[0][0],end=intervals[0][1];
        int len=intervals.length;
        for(int i=1;i<len;i++){
    
    
            //当选中的区间左端点大于当前区间的右端点时,两区间没有交集
            if(intervals[i][0]>end){
    
    
                //把当前区间左右端点添加到结果集中
                int []temp=new int[2];
                temp[0]=start;
                temp[1]=end;
                lists.add(temp);
                //更新当前区间左右端点
                start=intervals[i][0];
                end=intervals[i][1];
            //当选中的区间左端点小于等于当前区间的右端点时,两区间有交集
            }else{
    
    
                end=Math.max(intervals[i][1],end);
            }
        }
        //最终还需要把当前区间的左右端点添加到结果集中
        int []temp=new int[2];
        temp[0]=start;
        temp[1]=end;
        lists.add(temp);
        int reslen=lists.size();
        int [][]res=new int[reslen][2];
        //把动态数组的结果集加入到二维数组结果集中
        for(int i=0;i<reslen;i++){
    
    
            res[i][0]=lists.get(i)[0];
            res[i][1]=lists.get(i)[1];
        }
        return res;
    }

}

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/113810653