-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
48 lines (39 loc) · 1.5 KB
/
Copy pathsolution.java
File metadata and controls
48 lines (39 loc) · 1.5 KB
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
45
46
47
48
// 2276. Count Integers in Intervals
// https://leetcode.com/problems/count-integers-in-intervals/
// Hard | Java | Accepted 2026-08-13
// Runtime 80 ms | Memory 126 MB
class CountIntervals {
TreeMap<Integer, Integer> treemap = new TreeMap<>();
int count = 0;
public CountIntervals() {
}
public void add(int left, int right) {
// Find any interval that starts at or before `right`
// and could potentially overlap with [left, right]
Map.Entry<Integer, Integer> entry = treemap.floorEntry(right);
while (entry != null && entry.getValue() >= left) {
int start = entry.getKey();
int end = entry.getValue();
// Expand our new interval to absorb the overlapping one
left = Math.min(left, start);
right = Math.max(right, end);
// Subtract the old interval's length from total count and remove it
count -= (end - start + 1);
treemap.remove(start);
// Look for the next potential overlap
entry = treemap.floorEntry(right);
}
// Insert the fully merged interval and add its length
treemap.put(left, right);
count += (right - left + 1);
}
public int count() {
return count;
}
}
/**
* Your CountIntervals object will be instantiated and called as such:
* CountIntervals obj = new CountIntervals();
* obj.add(left,right);
* int param_2 = obj.count();
*/