File tree Expand file tree Collapse file tree 1 file changed +37
-1
lines changed
Expand file tree Collapse file tree 1 file changed +37
-1
lines changed Original file line number Diff line number Diff line change @@ -107,9 +107,45 @@ def intervalIntersection(A, B):
107107
108108![ labuladong] ( ../pictures/labuladong.jpg )
109109
110+ [ kingkong1111] ( https://github.com/kingkong1111 ) 提供 Java 代码:
111+
112+ ``` java
113+ public int [][] intervalIntersection(int [][] A , int [][] B ) {
114+ List<int[]> res = new ArrayList<> ();
115+ if (A == null || B == null ) {
116+ return res. toArray(new int [0 ][]);
117+ }
118+ // 定义两个指针遍历两个数组
119+ int i = 0 ;
120+ int j = 0 ;
121+ while (i < A . length && j < B . length) {
122+ int a1 = A [i][0 ];
123+ int a2 = A [i][1 ];
124+ int b1 = B [j][0 ];
125+ int b2 = B [j][1 ];
126+ // 1 说明有重合
127+ if (a1 <= b2 && a2 >= b1) {
128+ // 2 重合区间:前面的最大值 到 后面的最小值
129+ int start = Math . max(a1, b1);
130+ int end = Math . min(a2, b2);
131+ res. add(new int []{start, end});
132+ }
133+ // 3 哪个区间大,哪个不动,另一个指针动,看是否能扩大重合区间
134+ if (a2 > b2) {
135+ j++ ;
136+ } else {
137+ i++ ;
138+ }
139+ }
140+ return res. toArray(new int [0 ][]);
141+ }
142+ ```
110143
111144[ 上一篇:区间调度之区间合并问题] ( ../算法思维系列/区间调度问题之区间合并.md )
112145
113146[ 下一篇:信封嵌套问题] ( ../算法思维系列/信封嵌套问题.md )
114147
115- [ 目录] ( ../README.md#目录 )
148+ [ 目录] ( ../README.md#目录 )
149+
150+
151+
You can’t perform that action at this time.
0 commit comments