File tree 1 file changed +15
-22
lines changed
scripts/algorithms/I/Interval List Intersections
1 file changed +15
-22
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 6 ms (Top 9.49%) | Memory: 45.30 MB (Top 8.74%)
2
+
1
3
class Solution {
2
- public int [][] intervalIntersection (int [][] firstList , int [][] secondList ) {
3
- int i = 0 ;
4
- int j = 0 ;
5
-
4
+ public int [][] intervalIntersection (int [][] A , int [][] B ) {
6
5
List <int []> ans = new ArrayList <>();
7
-
8
- while (i <firstList .length && j <secondList .length ){
9
- int a [] = firstList [i ];
10
- int b [] = secondList [j ];
11
-
12
- if (b [0 ]<=a [1 ] && b [0 ]>=a [0 ])
13
- ans .add (new int []{b [0 ], Math .min (a [1 ], b [1 ])});
14
- else if (a [0 ]<=b [1 ] && a [0 ]>=b [0 ])
15
- ans .add (new int []{a [0 ], Math .min (a [1 ], b [1 ])});
16
-
17
- if (a [1 ]<=b [1 ])
18
- i ++;
19
- else
20
- j ++;
6
+ int i = 0 , j = 0 ;
7
+ while (i < A .length && j < B .length ){
8
+ int start = Math .max (A [i ][0 ], B [j ][0 ]);
9
+ int end = Math .min (A [i ][1 ], B [j ][1 ]);
10
+ if (start <= end ) ans .add (new int []{start , end });
11
+ if (A [i ][1 ]>B [j ][1 ]) j ++;
12
+ else i ++;
21
13
}
22
14
23
- int res [][] = new int [ans .size ()][2 ];
24
-
25
- for (i = 0 ; i < ans . size (); i ++ ){
26
- res [i ] = ans . get ( i ) ;
15
+ int [][] res = new int [ans .size ()][2 ];
16
+ i = 0 ;
17
+ for (int [] pair : ans ){
18
+ res [i ++ ] = pair ;
27
19
}
20
+
28
21
return res ;
29
22
}
30
23
}
You can’t perform that action at this time.
0 commit comments