710. Random Pick with Blacklist

思路:

生成[0,N)的数组,然后减去blacklist的名单,使用蓄水池算法,类似于382题的解法,但是最终超时了,也不知道有没有其他错误。

等待寻找更好的算法

class Solution {
public:
    Solution(int N, vector<int> blacklist) {
        
        for(int i=0;i<N;i++)mp[i]=i;
        
        for(int i=0;i<blacklist.size();i++){
            auto it=mp.find(blacklist[i]);
            if(it!=mp.end()) mp.erase(it);
        }
    }
    
    int pick() {
        int i=1;
        int choice=1;
        //for(auto it:mp){//这么写程序报错?问题得再找找
        for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
            int j=rand()%i;
            if(j==0) choice=it->second;
            i++;
        }
        return choice;
    }
private:
    map<int,int>mp;
};
原文地址:https://www.cnblogs.com/bright-mark/p/9603938.html