1488. Avoid Flood in The City

这篇博客介绍了一个算法,用于解决湖泊洪水问题。通过维护一个多重集和映射,算法利用二分查找在O(N)的时间复杂度内找到可能引发洪水的湖泊,并尝试寻找最早的晴天来避免洪水。解决方案涉及地图索引、二分搜索和数据结构的有效使用。
摘要由CSDN通过智能技术生成

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;
        
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值