forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
avoid-flood-in-the-city.cpp
32 lines (31 loc) · 1.01 KB
/
avoid-flood-in-the-city.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
vector<int> avoidFlood(vector<int>& rains) {
unordered_map<int, vector<int>> lookup;
for (int i = rains.size() - 1; i >= 0; --i) {
lookup[rains[i]].emplace_back(i);
}
vector<int> result;
priority_queue<int, vector<int>, greater<int>> min_heap;
for (int i = 0; i < rains.size(); ++i) {
if (rains[i]) {
if (lookup[rains[i]].size() >= 2) {
lookup[rains[i]].pop_back();
min_heap.emplace(lookup[rains[i]].back());
}
result.emplace_back(-1);
} else if (!min_heap.empty()) {
int j = min_heap.top(); min_heap.pop();
if (j < i) {
return {};
}
result.emplace_back(rains[j]);
} else {
result.emplace_back(1);
}
}
return min_heap.empty() ? result : vector<int>();
}
};