LeetCode986:区间列表的交集

如题

image-20220912201939434

  • 从示例1中可以发现,求两个闭区间的交集的时候,由于两个区间列表都是已经排序的,其实就是遍历firstListsecondList两个区间列表,然后从头开始依次对比两个区间列表的每一个子区间,找出这两个子区间的开始和结束端点的关系即可,总共有六种关系,下面结合代码解释:

      • firstLeft,firstRight表示第一个区间列表当前所指向区间的左右端点

      • secondLeft,secondRight表示第二个区间列表当前所指向区间的左右端点

  • class Solution {
        public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
            //用集合来保存临时结果,最后将它转成数组就行
            LinkedList<int[]> tempRes = new LinkedList<>();
            int n1 = firstList.length;
            int n2 = secondList.length;
            int i = 0, j = 0;
            while (i < n1 && j < n2) {
                int firstLeft = firstList[i][0];
                int firstRight = firstList[i][1];
                int secondLeft = secondList[j][0];
                int secondRight = secondList[j][1];
                //下面说的左右区间指的是第一个区间和第二个区间i和j当前指向的子区间
                //总共有六种情况,左右区间的右端点哪个更小,就让指针指向该区间数组的下一个区间
                //1:右区间全在左区间左边,无交集,此时右区间右移
                if (secondRight < firstLeft) {
                    j++;
                } 
                //2:右区间的右端点在左区间中间,左端点还在左区间左边,有交集,右区间继续右移
                else if (secondLeft < firstLeft && secondRight <= firstRight) {
                    tempRes.addLast(new int[]{firstLeft, secondRight});
                    j++;
                }
                //3:右区间被左区间覆盖,右区间继续右移
                else if (secondLeft >= firstLeft && secondRight <= firstRight) {
                    tempRes.addLast(new int[]{secondLeft, secondRight});
                    j++;
                }
                //4:左区间被右区间覆盖,此时左区间右移
                else if (secondLeft < firstLeft && secondRight > firstRight){
                    tempRes.addLast(new int[]{firstLeft,firstRight});
                    i++;
                }
                //5:右区间左端点在左区间中间,右端点在左区间右边,左区间继续右移
                else if (secondLeft <= firstRight && secondRight > firstRight) {
                    tempRes.addLast(new int[]{secondLeft, firstRight});
                    i++;
                } 
                //6:右区间整体在左区间右边,左区间右移
                else if (secondLeft > firstRight) {
                    i++;
                }
            }
            return tempRes.toArray(new int[0][0]);
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一酒。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值