-
Notifications
You must be signed in to change notification settings - Fork 46
/
_757.java
47 lines (39 loc) · 1.16 KB
/
_757.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.*;
/**
* LeetCode 757 - Set Intersection Size At Least Two
* <p>
* Sweepline + Greedy
* O(n log n)-time
*/
public class _757 {
public int intersectionSizeTwo(int[][] intervals) {
int n = intervals.length;
Arrays.sort(intervals, Comparator.<int[]>comparingInt(i -> i[1]).thenComparingInt(i -> i[0]));
TreeSet<Integer> set = new TreeSet<>();
for (int[] interval : intervals) {
int begin = interval[0], end = interval[1];
List<Integer> cand = new ArrayList<>();
for (int i : set.tailSet(begin)) {
if (i <= end) {
cand.add(i);
} else {
break;
}
if (cand.size() >= 2) {
break;
}
}
if (cand.size() == 0) {
set.add(end - 1);
set.add(end);
} else if (cand.size() == 1) {
if (!cand.contains(end)) {
set.add(end);
} else {
set.add(end - 1);
}
}
}
return set.size();
}
}