cs: add «729. My Calendar I»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-27 21:38:00 +02:00
parent f70fcffd6c
commit 528d2350aa
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

41
cs/my-calendar-i.cs Normal file
View 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;
}
}