Skip to content

Commit 186c945

Browse files
committed
Runtime: 17 ms (Top 28.66%) | Memory: 53.2 MB (Top 21.64%)
1 parent 88727f1 commit 186c945

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed
Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
// Runtime: 17 ms (Top 28.66%) | Memory: 53.2 MB (Top 21.64%)
12
//Time Complexity O(Nlog(N)) - N is the number of intervals
23
//Space Complexity O(N) - N is the number of intervals, can be reduced to O(1) if needed
34
class Solution {
45
public int intersectionSizeTwo(int[][] intervals) {
56
//corner case: can intervals be null or empty? No
6-
7+
78
//First, sort the intervals by end, then by reverse order start
89
Arrays.sort(intervals, new Comparator<int[]>() {
910
@Override
@@ -14,22 +15,22 @@ public int compare(int[] a, int[] b) {
1415
return a[1] - b[1];
1516
}
1617
});
17-
18+
1819
//Second, for each two intervals, greedily find if the previous interval would satisfy next interval's request
1920
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+
2122
//add last two nums within the range
2223
list.add(intervals[0][1] - 1);
2324
list.add(intervals[0][1]);
24-
25+
2526
for (int i = 1; i < intervals.length; i++) {
2627
int lastOne = list.get(list.size() - 1);
2728
int lastTwo = list.get(list.size() - 2);
28-
29+
2930
int[] interval = intervals[i];
3031
int start = interval[0];
3132
int end = interval[1];
32-
33+
3334
//if overlaps at least 2
3435
if (lastOne >= start && lastTwo >= start) {
3536
continue;
@@ -40,7 +41,7 @@ public int compare(int[] a, int[] b) {
4041
list.add(end);
4142
}
4243
}
43-
44-
return list.size();
44+
45+
return list.size();
4546
}
46-
}
47+
}

0 commit comments

Comments
 (0)