cs: add «729. My Calendar I»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
f70fcffd6c
commit
528d2350aa
1 changed files with 41 additions and 0 deletions
41
cs/my-calendar-i.cs
Normal file
41
cs/my-calendar-i.cs
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue