Avoid Flood in The City LeetCode solution in C++

1
class Solution {
2
public:
3
vector<int> avoidFlood(vector<int> &rains) {
4
vector<int> ans(rains.size(), -1);
5
unordered_map<int, int> indices; // store the lake and its index
6
set<int> st; // stores the indices of zeros
7

8
for (int i = 0; i < rains.size(); ++i) {
9
if (!rains[i])
10
st.insert(i);
11
else {
12
if (indices.find(rains[i]) == end(indices))
13
indices[rains[i]] = i;
14
else {
15
int prevDay = indices[rains[i]];
16
auto it = st.upper_bound(prevDay);
17
if (it == end(st)) return {};
18
ans[*it] = rains[i];
19
indices[rains[i]] = i;
20
st.erase(it);
21
}
22
}
23
}
24

25
for (int i = 0; i < ans.size(); ++i) {
26
if (!rains[i] and ans[i] == -1) ans[i] = 1;
27
}
28
return ans;
29
}
30
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0