1
+ // Runtime: 17 ms (Top 28.66%) | Memory: 53.2 MB (Top 21.64%)
1
2
//Time Complexity O(Nlog(N)) - N is the number of intervals
2
3
//Space Complexity O(N) - N is the number of intervals, can be reduced to O(1) if needed
3
4
class Solution {
4
5
public int intersectionSizeTwo (int [][] intervals ) {
5
6
//corner case: can intervals be null or empty? No
6
-
7
+
7
8
//First, sort the intervals by end, then by reverse order start
8
9
Arrays .sort (intervals , new Comparator <int []>() {
9
10
@ Override
@@ -14,22 +15,22 @@ public int compare(int[] a, int[] b) {
14
15
return a [1 ] - b [1 ];
15
16
}
16
17
});
17
-
18
+
18
19
//Second, for each two intervals, greedily find if the previous interval would satisfy next interval's request
19
20
List <Integer > list = new ArrayList <>(); //basically the ending set S, btw, we actually do not need this but I use it here for better intuition
20
-
21
+
21
22
//add last two nums within the range
22
23
list .add (intervals [0 ][1 ] - 1 );
23
24
list .add (intervals [0 ][1 ]);
24
-
25
+
25
26
for (int i = 1 ; i < intervals .length ; i ++) {
26
27
int lastOne = list .get (list .size () - 1 );
27
28
int lastTwo = list .get (list .size () - 2 );
28
-
29
+
29
30
int [] interval = intervals [i ];
30
31
int start = interval [0 ];
31
32
int end = interval [1 ];
32
-
33
+
33
34
//if overlaps at least 2
34
35
if (lastOne >= start && lastTwo >= start ) {
35
36
continue ;
@@ -40,7 +41,7 @@ public int compare(int[] a, int[] b) {
40
41
list .add (end );
41
42
}
42
43
}
43
-
44
- return list .size ();
44
+
45
+ return list .size ();
45
46
}
46
- }
47
+ }
0 commit comments