-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMyCalendarI.java
More file actions
69 lines (59 loc) · 1.82 KB
/
MyCalendarI.java
File metadata and controls
69 lines (59 loc) · 1.82 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package orderedmap;
// Source : https://leetcode.com/problems/my-calendar-i/
// Id : 729
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2020/8/12
// Topic : Ordered Map
// Level : Medium
// Other :
// Tips :
// Links :
// Result : 55.27% 19.51%
import java.util.*;
public class MyCalendarI {
//TLE
/*Set<Integer> booked;
public MyCalendarI() {
// public MyCalendar() {
this.booked = new HashSet<>();
}
public boolean book(int start, int end) {
int len = end - start;
Integer[] tmp = new Integer[len];
for (int i = 0; i < len; i++) {
if (booked.contains(start + i))
return false;
tmp[i] = start + i;
}
booked.addAll(Arrays.asList(tmp));
// use Integer[] instead of int[]
// as Arrays.asList(int[]) will internally consider int[] as a single element.
return true;
}*/
TreeMap<Integer, Integer> calendar;
// 55.27% 36 ms 19.51%
public MyCalendarI() {
// public MyCalendar() {
calendar = new TreeMap();
}
public boolean book(int start, int end) {
Integer prev = calendar.floorKey(start),
next = calendar.ceilingKey(start);
if ((prev == null || calendar.get(prev) <= start) &&
(next == null || end <= next)) {
calendar.put(start, end);
return true;
}
return false;
}
// // improved performance
// public boolean book1(int start, int end) {
// Map.Entry<Integer, Integer> e = calendar.lowerEntry(end); // the greatest key strictly less than the given key
// if (e != null && e.getValue() > start) {
// return false;
// } else {
// calendar.put(start, end);
// return true;
// }
// }
}