42 lines
1.2 KiB
C#
42 lines
1.2 KiB
C#
|
public class MyCalendar {
|
||
|
private record Meeting(int Start, int End) {
|
||
|
public bool Has(int x) => x > Start && x < End;
|
||
|
|
||
|
public static bool operator <(Meeting a, Meeting b) => a.Start < b.Start;
|
||
|
public static bool operator >(Meeting a, Meeting b) => a.Start > b.Start;
|
||
|
}
|
||
|
|
||
|
private static bool Overlaps(Meeting a, Meeting b)
|
||
|
=> a == b || a.Has(b.Start) || a.Has(b.End) || b.Has(a.Start) || b.Has(a.End);
|
||
|
|
||
|
private List<Meeting> meetings = [];
|
||
|
|
||
|
public MyCalendar() { }
|
||
|
|
||
|
public bool Book(int start, int end) {
|
||
|
meetings.Add(new Meeting(start, end));
|
||
|
|
||
|
var it = meetings.Count - 1;
|
||
|
|
||
|
for (
|
||
|
int i = meetings.Count - 1;
|
||
|
i > 0 && meetings[i - 1] > meetings[i];
|
||
|
--i, --it
|
||
|
) {
|
||
|
if (Overlaps(meetings[i], meetings[i - 1])) {
|
||
|
meetings.RemoveAt(it);
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
(meetings[i], meetings[i - 1]) = (meetings[i - 1], meetings[i]);
|
||
|
}
|
||
|
|
||
|
if (it > 0 && Overlaps(meetings[it], meetings[it - 1])) {
|
||
|
meetings.RemoveAt(it);
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
return true;
|
||
|
}
|
||
|
}
|