731. My Calendar II #617
-
Topics: You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking. A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers Implement the
Example 1:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to maintain two lists of bookings:
When a new event is requested, we need to check if it will cause a triple booking. To do that:
Finally, if the event passes both checks, we add it to the single bookings list. Let's implement this solution in PHP: 731. My Calendar II <?php
class MyCalendarTwo {
/**
* @var array
*/
private $singleBookings;
/**
* @var array
*/
private $doubleBookings;
/**
*/
function __construct() {
$this->singleBookings = [];
$this->doubleBookings = [];
}
/**
* @param Integer $start
* @param Integer $end
* @return Boolean
*/
function book($start, $end) {
// Check for overlap with double bookings (would result in triple booking)
foreach ($this->doubleBookings as $booking) {
$overlapStart = max($start, $booking[0]);
$overlapEnd = min($end, $booking[1]);
if ($overlapStart < $overlapEnd) {
// Overlap with a double booking, hence a triple booking will occur
return false;
}
}
// Check for overlap with single bookings and add overlap to double bookings
foreach ($this->singleBookings as $booking) {
$overlapStart = max($start, $booking[0]);
$overlapEnd = min($end, $booking[1]);
if ($overlapStart < $overlapEnd) {
// There is overlap, so add this overlap to double bookings
$this->doubleBookings[] = [$overlapStart, $overlapEnd];
}
}
// If no triple booking, add the event to single bookings
$this->singleBookings[] = [$start, $end];
return true;
}
}
/**
* Your MyCalendarTwo object will be instantiated and called as such:
* $obj = MyCalendarTwo();
* $ret_1 = $obj->book($start, $end);
*/
// Example Usage
$calendar = new MyCalendarTwo();
echo $calendar->book(10, 20) ? 'true' : 'false'; // true
echo "\n";
echo $calendar->book(50, 60) ? 'true' : 'false'; // true
echo "\n";
echo $calendar->book(10, 40) ? 'true' : 'false'; // true
echo "\n";
echo $calendar->book(5, 15) ? 'true' : 'false'; // false
echo "\n";
echo $calendar->book(5, 10) ? 'true' : 'false'; // true
echo "\n";
echo $calendar->book(25, 55) ? 'true' : 'false'; // true
echo "\n";
?> Explanation:
Time Complexity:
This solution efficiently handles up to 1000 calls to the |
Beta Was this translation helpful? Give feedback.
We need to maintain two lists of bookings:
When a new event is requested, we need to check if it will cause a triple booking. To do that:
Finally, if the event passes both checks, we add …