製作一個行事曆,起訖皆為整數,若行程不衝突則放入行事曆並回傳true,否則回傳false。
https://leetcode.com/problems/my-calendar-i/
範例Input
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20);
myCalendar.book(15, 25); //因(15,25)和(10, 20)衝突,回傳false且不放入行事曆
myCalendar.book(20, 30);
Output
[null, true, false, true][10,20] ↑x ↑ [15,20] ↑ ↑ [20,30]每次要放入新的行程時,都需要和最接近的區間比較,因此可以用有序的TreeMap來儲存。
寫成程式碼如下
TreeMap<Integer, Integer> myCalendar = new TreeMap<>();
public boolean book(int start, int end) {
//若行事曆不為空才比較
if (!myCalendar.isEmpty()) {
//確認左側是否有行程
Integer fs = myCalendar.floorKey(start);
if (fs != null && myCalendar.get(fs) > start) {
//不為空值才比較,確認左側行程是否大過新行程的開始
return false;
}
//確認右側是否有行程
Integer hs = myCalendar.higherKey(start);
if (hs != null && hs < end) {
//不為空值才比較,確認右側行程是否小於新行程的結束
return false;
}
}
//無行程衝突,放入此次行程
myCalendar.put(start, end);
return true;
}
沒有留言:
張貼留言