{"id":296,"date":"2017-09-16T23:44:34","date_gmt":"2017-09-17T06:44:34","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=296"},"modified":"2018-07-10T18:27:52","modified_gmt":"2018-07-11T01:27:52","slug":"leetcode-380-insert-delete-getrandom-o1","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-380-insert-delete-getrandom-o1\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 380. Insert Delete GetRandom O(1)"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 380. Insert Delete GetRandom O(1) - \u5237\u9898\u627e\u5de5\u4f5c EP57\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/y240Qh9H9uk?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>Design a data structure that supports all following operations in\u00a0<i>average<\/i>\u00a0<b>O(1)<\/b>\u00a0time.<\/p>\n<ol>\n<li><code>insert(val)<\/code>: Inserts an item val to the set if not already present.<\/li>\n<li><code>remove(val)<\/code>: Removes an item val from the set if present.<\/li>\n<li><code>getRandom<\/code>: Returns a random element from current set of elements. Each element must have the\u00a0<b>same probability<\/b>\u00a0of being returned.<\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<p><strong>Idea:<\/strong><\/p>\n<p>Hashtable + array<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-302\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-1-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-1-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-301\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-2.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-2.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-2-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-2-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-2-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-300\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-3.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-3.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-3-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-3-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/380-ep57-3-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><strong>Time complexity:<\/strong><\/p>\n<p>O(1)<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Solution:<\/strong><\/p>\n<pre class=\"lang:c++ decode:true  \">\/\/ Author: Huahua\r\n\/\/ Running time: 49 ms\r\nclass RandomizedSet {\r\npublic:\r\n    \/** Initialize your data structure here. *\/\r\n    RandomizedSet() {}\r\n    \r\n    \/** Inserts a value to the set. Returns true if the set did not already contain the specified element. *\/\r\n    bool insert(int val) {\r\n        if(m_.count(val)) return false;\r\n        m_[val] = vals_.size();\r\n        vals_.push_back(val);\r\n        return true;\r\n    }\r\n    \r\n    \/** Removes a value from the set. Returns true if the set contained the specified element. *\/\r\n    bool remove(int val) {\r\n        if(!m_.count(val)) return false;\r\n        int index = m_[val];\r\n        m_[vals_.back()] = index;\r\n        m_.erase(val);\r\n        std::swap(vals_[index], vals_.back());\r\n        vals_.pop_back();\r\n        return true;\r\n    }\r\n    \r\n    \/** Get a random element from the set. *\/\r\n    int getRandom() {\r\n        int index = rand() % vals_.size();\r\n        return vals_[index];\r\n    }\r\nprivate:\r\n    \/\/ val -&gt; index in the array\r\n    unordered_map&lt;int, int&gt; m_;\r\n    vector&lt;int&gt; vals_;\r\n};<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Related Problems:<\/strong><\/p>\n<ul>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-381-insert-delete-getrandom-o1-duplicates-allowed\/\">LeetCode 381. Insert Delete GetRandom O(1) &amp;#8211; Duplicates allowed<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-460-lfu-cache\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 460. LFU Cache O(1)<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-146-lru-cache\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 146. LRU Cache O(1)<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/leetcode\/leetcode-295-find-median-from-data-stream\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 295. Find Median from Data Stream O(logn) + O(1)<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Design a data structure that supports all following operations in\u00a0average\u00a0O(1)\u00a0time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[89,70],"tags":[20,82,92,91],"class_list":["post-296","post","type-post","status-publish","format-standard","hentry","category-data-structure","category-hashtable","tag-array","tag-hashtable","tag-o1","tag-random","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/296","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=296"}],"version-history":[{"count":8,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/296\/revisions"}],"predecessor-version":[{"id":3055,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/296\/revisions\/3055"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=296"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=296"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=296"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}