Leetcode 380. O(1) 时间插入、删除和获取随机元素(DAY 157)---- LeetCode 精选 TOP 面试题

ゞ 浴缸里的玫瑰 2022-09-09 04:49 79阅读 0赞

文章目录

    • 原题题目
    • 代码实现(首刷自解)

原题题目


在这里插入图片描述


代码实现(首刷自解)


  1. class RandomizedSet {
  2. public:
  3. /** Initialize your data structure here. */
  4. unordered_map<int,int> map;
  5. vector<int> v;
  6. RandomizedSet() { }
  7. /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
  8. bool insert(int val) {
  9. if(map.find(val) != map.end()) return false;
  10. v.emplace_back(val);
  11. map[val] = v.size()-1;
  12. return true;
  13. }
  14. /** Removes a value from the set. Returns true if the set contained the specified element. */
  15. bool remove(int val) {
  16. if(map.find(val) == map.end()) return false;
  17. swap(v[map[val]],v[v.size()-1]);
  18. v.pop_back();
  19. map[v[map[val]]] = map[val];
  20. map.erase(map.find(val));
  21. return true;
  22. }
  23. /** Get a random element from the set. */
  24. int getRandom() {
  25. int pos = rand()%v.size();
  26. return v[pos];
  27. }
  28. };
  29. /** * 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(); */

发表评论

表情:
评论列表 (有 0 条评论,79人围观)

还没有评论,来说两句吧...

相关阅读