-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1488.cpp
More file actions
71 lines (68 loc) · 2.02 KB
/
1488.cpp
File metadata and controls
71 lines (68 loc) · 2.02 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
public:
vector<int> avoidFlood(vector<int>& rains) {
int n = rains.size();
unordered_map<int, int> rain2day;
set<int> st;
vector<int> res(n, -1);
for (int i = 0; i < n; ++i) {
if (rains[i] > 0) {
if (!rain2day.count(rains[i])) {
rain2day[rains[i]] = i;
}
else {
int prev = rain2day[rains[i]];
auto it = st.upper_bound(prev);
if (it == st.end()) return {};
res[*it] = rains[i];
st.erase(it);
rain2day[rains[i]] = i;
}
}
else {
st.insert(i);
}
}
for (auto& num : st) res[num] = 1;
return res;
}
};
class Solution {
public:
vector<int> avoidFlood(vector<int>& rains) {
int n = rains.size();
unordered_map<int, vector<int>> mp;
unordered_map<int, int> rain2idx;
for (int i = 0; i < n; ++i) {
mp[rains[i]].push_back(i);
rain2idx[rains[i]] = 0;
}
vector<int> res(n, -1);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
for (int i = 0; i < n; ++i) {
if (rains[i] > 0) {
int rain = rains[i];
int index = rain2idx[rain];
// has next index
if (index + 1 < mp[rain].size()) {
pq.push({mp[rain][index + 1], rain});
rain2idx[rain]++;
}
}
else {
if (!pq.empty()) {
auto [index, rain] = pq.top();
pq.pop();
if (i > index) return {};
res[i] = rain;
}
else {
res[i] = 1;
}
}
}
if (!pq.empty()) {
return {};
}
return res;
};