Skip to content

Commit 2fc0830

Browse files
committed
Add solution #731
1 parent e1744d3 commit 2fc0830

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,7 @@
554554
728|[Self Dividing Numbers](./0728-self-dividing-numbers.js)|Easy|
555555
729|[My Calendar I](./0729-my-calendar-i.js)|Medium|
556556
730|[Count Different Palindromic Subsequences](./0730-count-different-palindromic-subsequences.js)|Hard|
557+
731|[My Calendar II](./0731-my-calendar-ii.js)|Medium|
557558
733|[Flood Fill](./0733-flood-fill.js)|Easy|
558559
735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium|
559560
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|

solutions/0731-my-calendar-ii.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 731. My Calendar II
3+
* https://leetcode.com/problems/my-calendar-ii/
4+
* Difficulty: Medium
5+
*
6+
* You are implementing a program to use as your calendar. We can add a new event if adding the
7+
* event will not cause a triple booking.
8+
*
9+
* A triple booking happens when three events have some non-empty intersection (i.e., some moment
10+
* is common to all the three events.).
11+
*
12+
* The event can be represented as a pair of integers startTime and endTime that represents a
13+
* booking on the half-open interval [startTime, endTime), the range of real numbers x such that
14+
* startTime <= x < endTime.
15+
*
16+
* Implement the MyCalendarTwo class:
17+
* - MyCalendarTwo() Initializes the calendar object.
18+
* - boolean book(int startTime, int endTime) Returns true if the event can be added to the calendar
19+
* successfully without causing a triple booking. Otherwise, return false and do not add the event
20+
* to the calendar.
21+
*/
22+
23+
var MyCalendarTwo = function() {
24+
this.bookings = [];
25+
this.overlaps = [];
26+
};
27+
28+
/**
29+
* @param {number} startTime
30+
* @param {number} endTime
31+
* @return {boolean}
32+
*/
33+
MyCalendarTwo.prototype.book = function(startTime, endTime) {
34+
for (const [start, end] of this.overlaps) {
35+
if (startTime < end && endTime > start) return false;
36+
}
37+
38+
for (const [start, end] of this.bookings) {
39+
if (startTime < end && endTime > start) {
40+
this.overlaps.push([Math.max(start, startTime), Math.min(end, endTime)]);
41+
}
42+
}
43+
44+
this.bookings.push([startTime, endTime]);
45+
return true;
46+
};

0 commit comments

Comments
 (0)