• 380. Insert Delete GetRandom O(1)


    1

    这题难点在于如何在删除的时候做到O1, 因为要随机访问毫无疑问你要用到数组加hash结构,感觉这确实是个新思路

    2

    新增和随机访问没什么好说的, 来看删除如何做到O1

    3

    问题 可以在hash里面保存元素对应的索引值, 但是如果删除了数组中间某个元素, 会导致后面的索引全部需要更新, 这样就不是O1了

    解决:  假如数组有10个元素 要删除第5个,  不要直接删除第5个, 这样后面的元素索引都会减1,  因此把第五个和最后一个元素交换位置, 同时更新hash里面的两个元素的value;

    最后删除数组最后一个元素.

    4

    如果删除的本来就是最后一个元素, 直接删除就好

     1 class RandomizedSet {
     2 public:
     3     unordered_map<int,int> kv;
     4     vector<int> index;
     5     /** Initialize your data structure here. */
     6     RandomizedSet() {
     7         srand(time(NULL));
     8     }
     9     
    10     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    11     bool insert(int val) {
    12         if(kv.find(val)!=kv.end())
    13             return false;
    14         index.push_back(val);
    15         kv[val]=index.size()-1;
    16         return true;
    17     }
    18     
    19     /** Removes a value from the set. Returns true if the set contained the specified element. */
    20     bool remove(int val) {
    21         auto iter=kv.find(val);
    22         if(iter==kv.end())return false;
    23         if(iter->second<index.size()-1)
    24         {
    25             kv[index.back()]=iter->second;
    26             index[iter->second]=index.back();
    27         }
    28             kv.erase(iter);
    29             index.pop_back();
    30         return true;
    31     }
    32     
    33     /** Get a random element from the set. */
    34     int getRandom() {
    35         return index[rand()%index.size()];
    36     }
    37 };
    38 
    39 /**
    40  * Your RandomizedSet object will be instantiated and called as such:
    41  * RandomizedSet obj = new RandomizedSet();
    42  * bool param_1 = obj.insert(val);
    43  * bool param_2 = obj.remove(val);
    44  * int param_3 = obj.getRandom();
    45  */
  • 相关阅读:
    递归---Day29
    File类---Day28
    线程池---Day26
    微信公众号运营人员必备的软件工具网站合集
    消息中间件的技术选型心得-RabbitMQ、ActiveMQ和ZeroMQ
    itoa函数的递归实现(二级指针实现)
    二叉树——查找两个任意节点的最近祖先
    C#多线程(二)
    C#多线程(一)
    Websocket协议之php实现
  • 原文地址:https://www.cnblogs.com/lychnis/p/9281384.html
Copyright © 2020-2023  润新知