From 60d577f0fb891e030229de87b8c9a3900e31784e Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Tue, 17 Dec 2019 21:40:10 +0800 Subject: [PATCH] Create 380. Insert Delete GetRandom O(1).md --- .../380. Insert Delete GetRandom O(1).md | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 solutions/380. Insert Delete GetRandom O(1).md diff --git a/solutions/380. Insert Delete GetRandom O(1).md b/solutions/380. Insert Delete GetRandom O(1).md new file mode 100644 index 0000000..ae905a0 --- /dev/null +++ b/solutions/380. Insert Delete GetRandom O(1).md @@ -0,0 +1,50 @@ +# [380. Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) + +# 思路 + +要求设计一个集合类,要在O(1)时间内插入、删除以及随机返回一个元素。 +如果不考虑随机返回一个元素的话,那么这个类就是`unordered_set`,它可以在常数时间复杂度进行插入和删除。 + +现在要考虑在常数时间返回一个随机元素,即要考虑以常数时间根据索引取值,满足这个特性的只有数组。所以我们以用`unordered_map`记录元素到数组索引的映射, +这样就可以在常数时间返回一个随机元素。不过为了以常数时间复杂度进行删除操作,需要变通一下:将待删除的元素和数组末元素交换一下,然后删除末尾元素。 + +> `rand()`产生0到RAND_MAX之间的随机数,在头文件stdlib.h内。 + +# C++ +``` C++ +class RandomizedSet { +private: + vectordata; + unordered_mapidx_map; + +public: + /** Initialize your data structure here. */ + RandomizedSet() {} + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + bool insert(int val) { + if(idx_map.count(val)) return false; + idx_map[val] = data.size(); + data.push_back(val); + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + bool remove(int val) { + if(!idx_map.count(val)) return false; + + int idx = idx_map[val]; + data[idx] = data.back(); + idx_map[data.back()] = idx; + + idx_map.erase(val); + data.pop_back(); + return true; + } + + /** Get a random element from the set. */ + int getRandom() { + return data[rand() % data.size()]; + } +}; +```