1. 题目来源
2. 题目说明
3. 题目解析
设计数据结构,实现三个操作:
- O ( 1 ) O(1) O(1) 插入
- O ( 1 ) O(1) O(1) 删除
- O ( 1 ) O(1) O(1) 等概率返回一个随机值
当然,插入、删除 O ( 1 ) O(1) O(1) 的话哈希表就能搞定,但是哈希表不支持等概率返回这个操作,需要有一个支持随机索引的数据结构,那么就是数组了。
开一个哈希表,建一个数组:
- 插入时在数组末尾插入,在哈希表中维护该数在数组下的下标,即
<val, index>
- 返回随机值,数组支持随机索引,等概率返回任一数即可
- 删除,哈希表可以
O
(
1
)
O(1)
O(1) 删除。数组仅支持末尾
O
(
1
)
O(1)
O(1) 删除。那么基于这个思想,我们可以把需要删除的数放到数组最后一个位置,然后直接
pop_back()
,达到 O ( 1 ) O(1) O(1) 删除。 当然,也需要在哈希表中将对应索引进行交换。
这也是数组实现 O ( 1 ) O(1) O(1) 删除一个元素的方法,将该元素与末尾元素进行交换后删除。
代码:
class RandomizedSet {
public:
unordered_map<int, int> hash;
vector<int> nums;
/** 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 (hash.count(val) == 0) {
nums.push_back(val);
hash[val] = nums.size() - 1;
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (hash.count(val)) {
int y = nums.back();
int pval = hash[val], py = hash[y];
swap(nums[pval], nums[py]);
swap(hash[val], hash[y]);
nums.pop_back();
hash.erase(val);
return true;
}
return false;
}
/** Get a random element from the set. */
int getRandom() {
return nums[rand() % nums.size()];
}
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/