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