Input: intervals =[[1,3],[1,4],[2,5],[3,5]]Output: 3Explanation: let nums =[2,3,4].It can be shown that there cannot be any containing array of size 2.
Input: intervals =[[1,2],[2,3],[2,4],[4,5]]Output: 5Explanation: let nums =[1,2,3,4,5].It can be shown that there cannot be any containing array of size 4.
To cover each interval with at least two numbers, we can process intervals in order of their end points. By always picking the largest possible numbers at the end of each interval, we maximize the chance that these numbers will also cover future intervals, minimizing the total set size.
import java.util.*;
classSolution {
publicintintersectionSizeTwo(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[1]== b[1]? b[0]- a[0] : a[1]- b[1]);
int ans = 0, last =-1, second =-1;
for (int[] it : intervals) {
int cnt = 0;
if (last >= it[0]&& last <= it[1]) cnt++;
if (second >= it[0]&& second <= it[1]) cnt++;
if (cnt == 2) continue;
if (cnt == 1) {
ans++;
second = last;
last = it[1];
} else {
ans += 2;
last = it[1];
second = it[1]- 1;
}
}
return ans;
}
}
classSolution {
funintersectionSizeTwo(intervals: Array<IntArray>): Int {
intervals.sortWith(compareBy({ it[1] }, { -it[0] }))
var ans = 0var last = -1var second = -1for (itin intervals) {
var cnt = 0if (last init[0]..it[1]) cnt++if (second init[0]..it[1]) cnt++when (cnt) {
2-> {}
1-> {
ans++ second = last
last = it[1]
}
else-> {
ans +=2 last = it[1]
second = it[1] - 1 }
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defintersectionSizeTwo(self, intervals: list[list[int]]) -> int:
intervals.sort(key=lambda x: (x[1], -x[0]))
ans = last = second =-1 res =0for it in intervals:
cnt = (last >= it[0] and last <= it[1]) + (second >= it[0] and second <= it[1])
if cnt ==2:
continueelif cnt ==1:
res +=1 second = last
last = it[1]
else:
res +=2 last = it[1]
second = it[1] -1return res