Leetcode Problem:
Summary
- Implementing a program to use as a calendar to avoid double booking.
Approach
- We use a vector of pairs to store the events in the calendar
- For each new event, we check if it intersects with any existing events
- If it does, we return false
- Otherwise, we add the new event to the calendar.
Complexity
- O(n) where n is the number of events in the calendar
Explain
- We define a struct _pair to store the start and end times of each event
- In the book function, we iterate over each event in the calendar
- If the end time of the new event is less than or equal to the start time of an existing event, or if the start time of the new event is greater than the end time of an existing event, we continue to the next event
- If we find an existing event that intersects with the new event, we return false
- Otherwise, we add the new event to the calendar by pushing it onto the vector of pairs and return true.
Solution Code:
struct _pair{
int start;
int end;
};
class MyCalendar {
public:
vector<_pair> v;
MyCalendar() {
}
bool book(int start, int end) {
for(_pair p : v){
if (end <= p.start || p.end <= start){
continue;
}
return false;
}
v.push_back({start, end});
return true;
}
};
/**
* Your MyCalendar object will be instantiated and called as such:
* MyCalendar* obj = new MyCalendar();
* bool param_1 = obj->book(start,end);
*/
'알고리즘' 카테고리의 다른 글
Design Circular Deque (0) | 2025.02.13 |
---|---|
My Calendar II (0) | 2025.02.13 |
Sum of Prefix Scores of Strings (0) | 2025.02.13 |
Max Sum of a Pair With Equal Sum of Digits (0) | 2025.02.12 |
Find the Length of the Longest Common Prefix (0) | 2025.02.12 |