[LeetCode] Avoid Flood in The City

1488. Avoid Flood in The City

Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.

Given an integer array rains where:

  • rains[i] > 0 means there will be rains over the rains[i] lake.
  • rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.

Return an array ans where:

  • ans.length == rains.length
  • ans[i] == -1 if rains[i] > 0.
  • ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.

If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.

Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. (see example 4)

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
class Solution {
private:
map<int, list<int>> getRainyDays(vector<int>& rains) {
map<int, list<int>> res;
for(int i = 0; i < rains.size(); i++) {
if(rains[i])
res[rains[i]].push_back(i);
}
return res;
}
public:
vector<int> avoidFlood(vector<int>& rains) {
map<int, list<int>> rainyDays = getRainyDays(rains);
map<int, int> lakes;
priority_queue<pair<int, int>> pq;
vector<int> ans(rains.size());

for(int i = 0; i < rains.size(); i++) {
if(rains[i]) {
lakes[rains[i]]++;
rainyDays[rains[i]].pop_front();
if(!rainyDays[rains[i]].empty())
pq.push(make_pair(-rainyDays[rains[i]].front(), rains[i]));

if(lakes[rains[i]] >= 2)
return vector<int> {};
ans[i] = -1;
} else {
if(pq.empty()) {
ans[i] = 1;
} else {
pair<int,int> dryLake = pq.top();
pq.pop();
ans[i] = dryLake.second;
lakes[dryLake.second]--;
}
}
}

return ans;
}
};
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
class Solution {
public:
vector<int> avoidFlood(vector<int>& rains) {
set<int> dryDays;
vector<int> res(rains.size(), 1);
map<int, int> rainedLakes;

for(int i = 0; i < rains.size(); i++) {
if(!rains[i])
dryDays.insert(i);
else {
auto isRained = rainedLakes.find(rains[i]);
if(isRained == rainedLakes.end()) {
res[i] = -1;
rainedLakes[rains[i]] = i;
} else {
auto hasDried = dryDays.upper_bound(isRained->second);
if(hasDried == dryDays.end())
return {};
res[*hasDried] = rains[i];
dryDays.erase(hasDried);
res[i] = -1;
rainedLakes[rains[i]] = i;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/17/PS/LeetCode/avoid-flood-in-the-city/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.