|
| 1 | +// Time: O(nlogn + mlogn) |
| 2 | +// Space: O(n) |
| 3 | + |
| 4 | +// line sweep, binary search |
| 5 | +class Solution { |
| 6 | +public: |
| 7 | + vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& persons) { |
| 8 | + map<int, int> cnt; |
| 9 | + for (const auto& flower : flowers) { |
| 10 | + ++cnt[flower[0]]; |
| 11 | + --cnt[flower[1] + 1]; |
| 12 | + } |
| 13 | + vector<int> prefix = {0}; |
| 14 | + vector<int> events; |
| 15 | + for (const auto& [k, v] : cnt) { |
| 16 | + events.emplace_back(k); |
| 17 | + prefix.emplace_back(prefix.back() + v); |
| 18 | + } |
| 19 | + vector<int> result; |
| 20 | + for (const auto& t : persons) { |
| 21 | + int i = distance(cbegin(events), upper_bound(cbegin(events), cend(events), t)); |
| 22 | + result.emplace_back(prefix[i]); |
| 23 | + } |
| 24 | + return result; |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +// Time: O(nlogn + mlogn) |
| 29 | +// Space: O(n) |
| 30 | +// binary search |
| 31 | +class Solution2 { |
| 32 | +public: |
| 33 | + vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& persons) { |
| 34 | + vector<int> starts, ends; |
| 35 | + for (const auto& flower : flowers) { |
| 36 | + starts.emplace_back(flower[0]); |
| 37 | + ends.emplace_back(flower[1] + 1); |
| 38 | + } |
| 39 | + sort(begin(starts), end(starts)); |
| 40 | + sort(begin(ends), end(ends)); |
| 41 | + vector<int> result; |
| 42 | + for (const auto& t : persons) { |
| 43 | + result.emplace_back(distance(cbegin(starts), upper_bound(cbegin(starts), cend(starts), t)) - |
| 44 | + distance(cbegin(ends), upper_bound(cbegin(ends), cend(ends), t))); |
| 45 | + } |
| 46 | + return result; |
| 47 | + } |
| 48 | +}; |
0 commit comments