本文主要是介绍C++ | Leetcode C++题解之第381题O(1)时间插入、删除和获取随机元素-允许重复,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class RandomizedCollection {
public:unordered_map<int, unordered_set<int>> idx;vector<int> nums;/** Initialize your data structure here. */RandomizedCollection() {}/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */bool insert(int val) {nums.push_back(val);idx[val].insert(nums.size() - 1);return idx[val].size() == 1;}/** Removes a value from the collection. Returns true if the collection contained the specified element. */bool remove(int val) {if (idx.find(val) == idx.end()) {return false;}int i = *(idx[val].begin());nums[i] = nums.back();idx[val].erase(i);idx[nums[i]].erase(nums.size() - 1);if (i < nums.size() - 1) {idx[nums[i]].insert(i);}if (idx[val].size() == 0) {idx.erase(val);}nums.pop_back();return true;}/** Get a random element from the collection. */int getRandom() {return nums[rand() % nums.size()];}
};
这篇关于C++ | Leetcode C++题解之第381题O(1)时间插入、删除和获取随机元素-允许重复的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!