• 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. */

  • 相关阅读:
    实现更低功耗R5F51406BDNE、R5F51406ADFK、R5F51406ADFL、R5F51406AGFN搭载RXv2内核的32位微控制器
    C# Linq增强扩展MoreLinq之Acquire
    【2022杭电多校3】2022“杭电杯”中国大学生算法设计超级联赛(3)
    kafka消费端消息去重方案
    Vue3 国际化i18n
    Spring Cloud Alibaba微服务第22章之Oauth2
    分享关于职场心态
    【Zookeeper专题】Zookeeper选举Leader源码解析
    光致发光荧光量子检测的作用
    【网络安全产品】---网闸
  • 原文地址:https://blog.csdn.net/qq_15711195/article/details/126456464