Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
insert-delete-getrandom-o1.cpp 1.21 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-08-04 13:07 +08:00 . Create insert-delete-getrandom-o1.cpp
// Time: O(1)
// Space: O(n)
class RandomizedSet {
public:
/** Initialize your data structure here. */
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (used_.count(val)) {
return false;
}
set_.emplace_back(val);
used_[val] = set_.size() - 1;
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (!used_.count(val)) {
return false;
}
used_[set_.back()] = used_[val];
swap(set_[used_[val]], set_.back());
used_.erase(val);
set_.pop_back();
return true;
}
/** Get a random element from the set. */
int getRandom() {
return set_[rand() % set_.size()];
}
private:
vector<int> set_;
unordered_map<int, int> used_;
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* bool param_1 = obj.insert(val);
* bool param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助