Count Integers in Intervals solution leetcode
Given an empty set of intervals, implement a data structure that can:
- Add an interval to the set of intervals.
- Count the number of integers that are present in at least one interval.
Implement the CountIntervals
class:
CountIntervals()
Initializes the object with an empty set of intervals.void add(int left, int right)
Adds the interval[left, right]
to the set of intervals.int count()
Returns the number of integers that are present in at least one interval.
Note that an interval [left, right]
denotes all the integers x
where left <= x <= right
.
-
- For each violating participant, the first 10 users who submit the violation report towards this participant will each earn 20 LeetCoins.
- Each user can earn up to 100 LeetCoins for reporting violations in a contest.
- Users will not be rewarded LeetCoins for reports on LCCN users.
Example 1: You can fill out the contact information at the registration step. LeetCode may reach out to eligible contest winners for an interview opportunity with LeetCode.
⭐ Bonus Prizes⭐
- Contestants ranked 1st will win a Apple HomePod mini
- Contestants ranked 2nd will win a Logitech G903 LIGHTSPEED Gaming Mouse
- Contestants ranked 3rd ~ 5th will win a LeetCode Backpack
- Contestants ranked 6th ~ 10th will win a LeetCode water bottle
- Contestants ranked 11th ~ 20th will win a LeetCode Big O Notebook
Only LCUS(leetcode.com) accounts are eligible for the bonus rewards. After the ranking is finalized, a LeetCode team member will reach out to you through email regarding the gift!
Count Integers in Intervals solution leetcode
Input ["CountIntervals", "add", "add", "count", "add", "count"] [[], [2, 3], [7, 10], [], [5, 8], []] Output [null, null, null, 6, null, 8] Explanation CountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. countIntervals.add(2, 3); // add [2, 3] to the set of intervals. countIntervals.add(7, 10); // add [7, 10] to the set of intervals. countIntervals.count(); // return 6 // the integers 2 and 3 are present in the interval [2, 3]. // the integers 7, 8, 9, and 10 are present in the interval [7, 10]. countIntervals.add(5, 8); // add [5, 8] to the set of intervals. countIntervals.count(); // return 8 // the integers 2 and 3 are present in the interval [2, 3]. // the integers 5 and 6 are present in the interval [5, 8]. // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10]. // the integers 9 and 10 are present in the interval [7, 10].
Constraints:
Count Integers in Intervals solution leetcode
1 <= left <= right <= 109
- At most
105
calls in total will be made toadd
andcount
. - At least one call will be made to
count
.
Solution
“Click here“