常数时间删除-查找数组中的任意元素
380. O(1) 时间插入、删除和获取随机元素
class RandomizedSet {
private:
vector<int> nums;
unordered_map<int, int> num2index;
public:
RandomizedSet() {
srand(time(0));
}
bool insert(int val) {
if (num2index.count(val)) {
return false;
}
num2index.emplace(val, nums.size());
nums.push_back(val);
return true;
}
bool remove(int val) {
if (!num2index.count(val)) {
return false;
}
int index = num2index[val];
int lastIndex = nums.size() - 1;
if (index != lastIndex) {
nums[index] = nums[lastIndex];
num2index[nums[index]] = index;
}
num2index.erase(val);
nums.pop_back();
return true;
}
int getRandom() {
int randIndex = rand() % nums.size();
return nums[randIndex];
}
};
710. 黑名单中的随机数
class Solution {
private:
int N_n, N_blacklist;
vector<int> nums;
unordered_map<int, int> black2num;
public:
Solution(int n, vector<int>& blacklist) {
srand(time(0));
N_n = n; N_blacklist = blacklist.size();
for (int num : blacklist) {
black2num.emplace(num, num);
}
int i = N_n - 1;
for (auto& it : black2num) {
if (it.first >= N_n - N_blacklist) continue;
while (black2num.count(i)) i--;
it.second = i;
i--;
}
}
int pick() {
int randNum = rand() % (N_n - N_blacklist);
if (black2num.count(randNum)) {
randNum = black2num[randNum];
}
return randNum;
}
};
标签:return,val,nums,int,blacklist,查找,数组,num2index,LBLD
From: https://www.cnblogs.com/yangxuanzhi/p/17327589.html