• LeetCode-380. Insert Delete GetRandom O(1) [C++][Java]


    LeetCode-380. Insert Delete GetRandom O(1)Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/insert-delete-getrandom-o1/

    Implement the RandomizedSet class:

    • RandomizedSet() Initializes the RandomizedSet object.
    • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
    • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
    • int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

    You must implement the functions of the class such that each function works in average O(1) time complexity.

    Example 1:

    Input
    ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
    [[], [1], [2], [2], [], [1], [2], []]
    Output
    [null, true, false, true, 2, true, false, 2]
    
    Explanation
    RandomizedSet randomizedSet = new RandomizedSet();
    randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
    randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
    randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
    randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
    randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
    randomizedSet.insert(2); // 2 was already in the set, so return false.
    randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
    

    Constraints:

    • -2^31 <= val <= 2^31 - 1
    • At most 2 * 10^5 calls will be made to insertremove, and getRandom.
    • There will be at least one element in the data structure when getRandom is called.

    【C++】

    1. class RandomizedSet {
    2. unordered_map<int, int> indexLookup{};
    3. vector<int> vals{};
    4. minstd_rand rng{};
    5. public:
    6. bool insert(const int val) {
    7. auto[iter, succeeded] = indexLookup.emplace(val, vals.size());
    8. if(!succeeded) { return false; }
    9. vals.emplace_back(val);
    10. return true;
    11. }
    12. bool remove(const int val) {
    13. auto doomed = indexLookup.find(val);
    14. if(doomed == indexLookup.cend()) { return false;}
    15. indexLookup[vals.back()] = doomed->second;
    16. vals[doomed->second] = vals.back();
    17. indexLookup.erase(doomed);
    18. vals.pop_back();
    19. return true;
    20. }
    21. int getRandom() {
    22. // int distribution is an inclusive range, so size - 1
    23. return vals[uniform_int_distribution<size_t>(0, vals.size()-1)(rng)];
    24. }
    25. };
    26. /**
    27. * Your RandomizedSet object will be instantiated and called as such:
    28. * RandomizedSet* obj = new RandomizedSet();
    29. * bool param_1 = obj->insert(val);
    30. * bool param_2 = obj->remove(val);
    31. * int param_3 = obj->getRandom();
    32. */

    【Java】

    1. class RandomizedSet {
    2. private List list;
    3. private HashMap valToIndex;
    4. private Random random;
    5. public RandomizedSet() {
    6. list = new ArrayList<>();
    7. valToIndex = new HashMap<>();
    8. random = new Random();
    9. }
    10. public boolean insert(int val) {
    11. if(valToIndex.containsKey(val)){
    12. return false;
    13. }
    14. list.add(val);
    15. valToIndex.put(val, list.size() - 1);
    16. return true;
    17. }
    18. public boolean remove(int val) {
    19. if(!valToIndex.containsKey(val)){
    20. return false;
    21. }
    22. int index = valToIndex.get(val);
    23. int last = list.get(list.size() - 1);
    24. list.set(index, last);
    25. list.remove(list.size() - 1);
    26. valToIndex.put(last, index);
    27. valToIndex.remove(val);
    28. return true;
    29. }
    30. public int getRandom() {
    31. return list.get(random.nextInt(list.size()));
    32. }
    33. }
    34. /**
    35. * Your RandomizedSet object will be instantiated and called as such:
    36. * RandomizedSet obj = new RandomizedSet();
    37. * boolean param_1 = obj.insert(val);
    38. * boolean param_2 = obj.remove(val);
    39. * int param_3 = obj.getRandom();
    40. */

  • 相关阅读:
    5G商企专网,助力打造城市生命线“安徽样板”
    复制带随机指针的链表
    前端知识学习案例9-开发企业网站9-实现关于我们的部分2
    Ansible概述和模块解释
    win11 已经配置好环境变量,但在命令行输入python/pip仍然出错
    量子计算(八):观测量和计算基下的测量
    15天学会AI应用开发(三)把历史对话作为提示词会怎样
    盒子阴影和网页布局
    MCP 实战入门:用一个 demo 讲清 agent 如何调用工具
    优化控制学习
  • 原文地址:https://blog.csdn.net/qq_15711195/article/details/126456464