Sponsored
Sponsored
This approach involves sorting the start and end times of the flowers separately. For each person’s arrival time, we use binary search to determine how many flowers have started blooming and how many have stopped. The difference will give us the number of flowers in full bloom.
Time Complexity: O((m + n) log m), where m is the number of flowers and n is the number of people.
Space Complexity: O(m), since we store the start and end times separately.
1#include <algorithm>
2#include <vector>
3
4using namespace std;
5
6vector<int> numberOfFlowersInFullBloom(vector<vector<int>>& flowers, vector<int>& people) {
7 vector<int> startTimes, endTimes;
8 for (const auto& flower : flowers) {
9 startTimes.push_back(flower[0]);
10 endTimes.push_back(flower[1]);
11 }
12 sort(startTimes.begin(), startTimes.end());
13 sort(endTimes.begin(), endTimes.end());
14 vector<int> result;
15 for (auto time : people) {
16 int startCount = upper_bound(startTimes.begin(), startTimes.end(), time) - startTimes.begin();
17 int endCount = lower_bound(endTimes.begin(), endTimes.end(), time) - endTimes.begin();
18 result.push_back(startCount - endCount);
19 }
20 return result;
21}
22
23// Example usage:
24// vector<vector<int>> flowers = {{1,6},{3,7},{9,12},{4,13}};
25// vector<int> people = {2,3,7,11};
26// auto answer = numberOfFlowersInFullBloom(flowers, people);
27// for(auto res : answer) cout << res << " \n";
This C++ solution employs similar logic to the Python solution. It uses upper_bound
and lower_bound
to locate the correct positions in the sorted start and end time lists, determining the count of flowers blooming at each person’s arrival.
This approach optimizes the flower counting by utilizing a two-pointer method after sorting both the start and end times, as well as people’s arrival times. This helps reduce unnecessary recomputation and simplifies the logic.
Time Complexity: O(m log m + n log n), where m is the number of flowers and n is the number of people, containing costs for sorting and linear traversal.
Space Complexity: O(m + n), for holding sorted intervals and the result array.
1function numberOfFlowersInFullBloom(flowers, people) {
2 const starts = flowers.map
This JavaScript solution employs the two-pointer technique to traverse sorted start and end times while adjusting the count of currently blooming flowers. The people’s arrival times are first mapped to their original indices and sorted, ensuring the results are recorded in the correct order.