1. We first use a multiset to store all the index of the sunny day
2. We second store the lake in a map using the index as a value
3. When we find a lake that already existed on the map, meaning that it would flood, we try to find the first sunny day after this. Try to erase the sunny that used to dry and also put the day we dried into the answer array.
As searching a number in multiset cost O(N), so we use binary search to reduce the time complexity.
class Solution {
public:
vector<int> avoidFlood(vector<int>& r) {
//binary search on
//1. put all the indices of 0 value of r[i] into set s;
//2. put all other indices into map, and use its value as key
//3. once we found that the r[i] is in the map, it means the lake is flooding.
//4. we find the index of same lake but in the previous hand
//5. use this index x to find the first element that larger than x, wecall it y
//6. we use y to change our ans vector.
int n = r.size();
map<int, int> m;
multiset<int> s;
vector<int> v;
for(int i = 0; i < n; i++){
if(!r[i]){
s.insert(i);
v.push_back(1);
}
else{
int lk = r[i];
if(m.find(lk)!=m.end()){
auto it = s.lower_bound(m[lk]);
if(it == s.end())return {};
int pos = *it;
v[pos] = lk;
s.erase(pos);
}
m[lk] = i;
v.push_back(-1);
}
}
return v;
}
}