Interval List Intersections

Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.  The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval.  For example, the intersection of [1, 3] and [2, 4] is [2, 3].)

 

Example 1:

Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.

 

Note:

  1. 0 <= A.length < 1000
  2. 0 <= B.length < 1000
  3. 0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9

题目理解:

定义区间:包含起始值和结束值的的一个闭区间,起始值小于或等于结束值。

给定两个区间集合,计算两个区间集合的交集,交集的定义类似于整数值集合的交集,具体可以结合上图理解

解题思路:

首先给两个区间集合按照起始值进行排序(按照结束值排序也可以),然后分别使用a指针和b指针指向两个区间集合中的区间,如果a和b有交集,那么这个交集i的起始值一定是max{a.start,b.start},也就是a和b起始值的最大值,交集i的结束值一定是min{a.end,b.end},也就是a和b结束值的最小值,这一点可以画图理解。

在计算完交集之后,对a和b进行更新,从a和b当中删除相交的部分。更新的具体方法是,将a.start=max{a.start,i.end},b.start=max{b.start,i.end},这一点也可以画图理解,主要是为了考虑a和b没有交集的情况,将交集的处理和更新的处理统一起来。

如果a或者b不满足区间的要求,即起始值大于结束值,则将指针指向下一个区间元素

代码如下:

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
class Solution {
    public Interval[] intervalIntersection(Interval[] A, Interval[] B) {
        Comparator comp = new Comparator(){
            public int compare(Interval a, Interval b){
                return a.start - b.start;
            }
        };
        if(A.length == 0 || B.length == 0)
            return new Interval[]{};
        Arrays.sort(A, comp);
        Arrays.sort(B, comp);
        int posa = 0, posb = 0;
        Interval a = A[posa], b = B[posb];
        List list = new ArrayList<>();
        while(true){
            int s = Math.max(a.start, b.start), e = Math.min(a.end, b.end);
            if(s <= e)
                list.add(new Interval(s, e));
            a.start = Math.max(a.start, e + 1);
            if(a.start > a.end){
                posa++;
                if(posa >= A.length)
                    break;
                a = A[posa];
            }
            b.start = Math.max(b.start, e + 1);
            if(b.start > b.end){
                posb++;
                if(posb >= B.length)
                    break;
                b = B[posb];
            }
        }
        Interval[] res = new Interval[list.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = list.get(i);
        return res;
    }
}

 

你可能感兴趣的:(LeetCode,LeetCode)