https://leetcode.com/contest/weekly-contest-194/problems/avoid-flood-in-the-city/
2.Idea
set lower bound
3.Source
class Solution {
public:
vector<int> avoidFlood(vector<int>& rains) {
int n = rains.size();
vector<int> emt, ans;
if (n == 0) return emt;
set<int> st;
map<int, int> mp;
ans.resize(n, -1);
for (int i = 0; i < n; i++) {
if (rains[i] == 0) {
st.insert(i);
}
else {
int cur = rains[i];
if (mp.find(cur) == mp.end()) {
mp[cur] = i;
}
else {
if (st.size() == 0) return emt;
set<int>::iterator it = st.lower_bound(mp[cur]);
if (it == st.end()) return emt;
else {
ans[*it] = cur;
st.erase(*it);
mp[cur] = i;
}
}
}
}
for (int i = 0; i < n; i++) {
if (rains[i] > 0) ans[i] = -1;
else if (ans[i] == -1) ans[i] = 1;
}
return ans;
}
};
No comments:
Post a Comment