2022-5-6 双指针
给定两个由一些 闭区间 组成的列表,firstList 和 secondList ,其中 firstList[i] = [starti, endi] 而 secondList[j] = [startj, endj] 。每个区间列表都是成对 不相交 的,并且 已经排序 。
返回这 两个区间列表的交集 。
形式上,闭区间 [a, b](其中 a <= b)表示实数 x 的集合,而 a <= x <= b 。
两个闭区间的 交集 是一组实数,要么为空集,要么为闭区间。例如,[1, 3] 和 [2, 4] 的交集为 [2, 3] 。
1 class Solution { 2 public int[][] intervalIntersection(int[][] firstList, int[][] secondList) { 3 List<int[]> list=new ArrayList<>(); 4 int point1=0,point2=0,n1=firstList.length,n2=secondList.length; 5 while (point1<n1&&point2<n2){ 6 // 不相交,且第一个数组在前面 7 if (firstList[point1][1]<secondList[point2][0]){ 8 point1++; 9 }else if (firstList[point1][0]>secondList[point2][1]){ 10 // 不相交,且第二个数组在前面 11 point2++; 12 }else if (firstList[point1][0]<=secondList[point2][0]&&firstList[point1][1]>=secondList[point2][1]){ 13 // 包含第二个 14 list.add(new int[]{secondList[point2][0],secondList[point2][1]}); 15 point2++; 16 }else if (firstList[point1][0]>=secondList[point2][0]&&firstList[point1][1]<=secondList[point2][1]){ 17 // 包含第一个 18 list.add(new int[]{firstList[point1][0],firstList[point1][1]}); 19 point1++; 20 }else if (firstList[point1][0]<=secondList[point2][0]){ 21 // 相交 第一个在前 22 list.add(new int[]{secondList[point2][0],firstList[point1][1]}); 23 point1++; 24 }else{ 25 list.add(new int[]{firstList[point1][0],secondList[point2][1]}); 26 point2++; 27 } 28 } 29 30 int len=list.size(); 31 int[][] res=new int[len][2]; 32 for (int i=0;i<list.size();i++){ 33 int[] x=list.get(i); 34 res[i][0]=x[0]; 35 res[i][1]=x[1]; 36 } 37 return res; 38 } 39 }
思路:讨论两个区间的所有情况,利用两个指针来 遍历。
浙公网安备 33010602011771号