LeetCode-Interval List Intersections

Description:
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:

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

题意:给定两个序列,每个序列中的元素为一个闭合区间,要求计算这两个序列中所有元素的交集;

解法:因为序列中的元素区间已经按照坐标的大小排好序了,所以我们只需要同时遍历这两个序列,对每两个元素求取他们的区间交集;所以,问题的重点在于如何求解两个区间的交集,我们知道,如果两个区间有交集,那么其开始端一定是两个区间开始端的最大值,结束端一定是两个区间的结束端的最小值,如下如图所示
在这里插入图片描述

Java
/**
 * 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) {
        List<Interval> res = new ArrayList<>();
        int pa = 0;
        int pb = 0;
        while (pa < A.length && pb < B.length) {
            int st = Math.max(A[pa].start, B[pb].start);
            int ed = Math.min(A[pa].end, B[pb].end);
            if (st <= ed) {
                res.add(new Interval(st, ed));
            }
            if (A[pa].end < B[pb].end) {
                pa++;
            } else {
                pb++;
            }
        }
        
        return res.toArray(new Interval[res.size()]);
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值