



看看题目 给出答案 要详细具体正确
看看题目 给出答案 要详细具体正确
看看题目 给出答案 要详细具体正确
关注让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言题目描述: 实现一个数据结构,支持以下操作:
import random
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.val_to_index = {}
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.val_to_index:
return False
self.nums.append(val)
self.val_to_index[val] = len(self.nums) - 1
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 not in self.val_to_index:
return False
last_val = self.nums[-1]
index = self.val_to_index[val]
self.nums[index] = last_val
self.val_to_index[last_val] = index
self.nums.pop()
del self.val_to_index[val]
return True
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
return random.choice(self.nums)
Java:
class RandomizedSet {
List<Integer> nums;
Map<Integer, Integer> valToIndex;
/** Initialize your data structure here. */
public RandomizedSet() {
nums = new ArrayList<>();
valToIndex = new HashMap<>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if (valToIndex.containsKey(val)) {
return false;
}
nums.add(val);
valToIndex.put(val, nums.size() - 1);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (!valToIndex.containsKey(val)) {
return false;
}
int index = valToIndex.get(val);
int lastVal = nums.get(nums.size() - 1);
nums.set(index, lastVal);
valToIndex.put(lastVal, index);
nums.remove(nums.size() - 1);
valToIndex.remove(val);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return nums.get(new Random().nextInt(nums.size()));
}
}