comments | edit_url |
---|---|
true |
设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构:
insert(val)
:当元素val
不存在时返回true
,并向集合中插入该项,否则返回false
。remove(val)
:当元素val
存在时返回true
,并从集合中移除该项,否则f返回true
。getRandom
:随机返回现有集合中的一项。每个元素应该有 相同的概率 被返回。
示例 :
输入: inputs = ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] [[], [1], [2], [2], [], [1], [2], []] 输出: [null, true, false, true, 2, true, false, 2] 解释: RandomizedSet randomSet = new RandomizedSet(); // 初始化一个空的集合 randomSet.insert(1); // 向集合中插入 1 , 返回 true 表示 1 被成功地插入 randomSet.remove(2); // 返回 false,表示集合中不存在 2 randomSet.insert(2); // 向集合中插入 2 返回 true ,集合现在包含 [1,2] randomSet.getRandom(); // getRandom 应随机返回 1 或 2 randomSet.remove(1); // 从集合中移除 1 返回 true 。集合现在包含 [2] randomSet.insert(2); // 2 已在集合中,所以返回 false randomSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2
提示:
-231 <= val <= 231 - 1
- 最多进行
2 * 105
次insert
,remove
和getRandom
方法调用 - 当调用
getRandom
方法时,集合中至少有一个元素
注意:本题与主站 380 题相同:https://leetcode.cn/problems/insert-delete-getrandom-o1/
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.a = []
self.m = {}
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val in self.m:
return False
self.m[val] = len(self.a)
self.a.append(val)
return True
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val in self.m:
idx = self.m[val]
self.a[idx], self.a[-1] = self.a[-1], self.a[idx]
self.m[self.a[idx]] = idx
self.a.pop()
del self.m[val]
return True
return False
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
return random.choice(self.a)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
class RandomizedSet {
private final Map<Integer, Integer> m;
private final List<Integer> a;
/** Initialize your data structure here. */
public RandomizedSet() {
this.m = new HashMap<>();
this.a = new ArrayList<>();
}
/**
* Inserts a value to the set. Returns true if the set did not already contain the specified
* element.
*/
public boolean insert(int val) {
if (this.m.containsKey(val)) {
return false;
}
this.m.put(val, this.a.size());
this.a.add(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (this.m.containsKey(val)) {
int idx = this.m.get(val), last = this.a.size() - 1;
Collections.swap(this.a, idx, last);
this.m.put(this.a.get(idx), idx);
this.a.remove(last);
this.m.remove(val);
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
return this.a.get(ThreadLocalRandom.current().nextInt(this.a.size()));
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
class RandomizedSet {
unordered_map<int, int> mp;
vector<int> nums;
public:
RandomizedSet() {
}
bool insert(int val) {
if (mp.count(val))
return false;
mp[val] = nums.size();
nums.push_back(val);
return true;
}
bool remove(int val) {
if (!mp.count(val))
return false;
int removeIndex = mp[val];
nums[removeIndex] = nums.back();
mp[nums.back()] = removeIndex;
mp.erase(val);
nums.pop_back();
return true;
}
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();
*/
class RandomizedSet {
private var m: [Int: Int]
private var a: [Int]
init() {
self.m = [Int: Int]()
self.a = [Int]()
}
func insert(_ val: Int) -> Bool {
if m[val] != nil {
return false
}
m[val] = a.count
a.append(val)
return true
}
func remove(_ val: Int) -> Bool {
if let idx = m[val] {
let last = a.count - 1
if idx != last {
a.swapAt(idx, last)
m[a[idx]] = idx
}
a.removeLast()
m.removeValue(forKey: val)
return true
}
return false
}
func getRandom() -> Int {
return a[Int.random(in: 0..<a.count)]
}
}
/* let obj = RandomizedSet()
* let param_1 = obj.insert(val)
* let param_2 = obj.insert(val)
* let param_3 = obj.remove(val)
* let param_4 = obj.getRandom()
*/