linux中SGID許可權
實現RandomizedSet 類:
RandomizedSet() 初始化 RandomizedSet 物件
bool insert(int val) 當元素 val 不存在時,向集合中插入該項,並返回 true ;否則,返回 false 。
bool remove(int val) 當元素 val 存在時,從集合中移除該項,並返回 true ;否則,返回 false 。
int getRandom() 隨機返回現有集合中的一項(測試用例保證呼叫此方法時集合中至少存在一個元素)。每個元素應該有 相同的概率 被返回。
你必須實現類的所有函式,並滿足每個函式的 平均 時間複雜度為 O(1) 。
示例:
輸入
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
輸出
[null, true, false, true, 2, true, false, 2]
解釋
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合現在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 應隨機返回 1 或 2 。
randomizedSet.remove(1); // 從集合中移除 1 ,返回 true 。集合現在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由於 2 是集合中唯一的數字,getRandom 總是返回 2 。
提示:
- -231 <= val <= 231 - 1
- 最多呼叫 insert、remove 和 getRandom 函式 2 * 105 次
- 在呼叫 getRandom 方法時,資料結構中 至少存在一個 元素。
方法一:變長陣列 + 雜湊
class RandomizedSet { List<Integer> list; Map<Integer, Integer> map; Random random; public RandomizedSet() { list = new ArrayList<>(); map = new HashMap<>(); random = new Random(); } public boolean insert(int val) { if (map.containsKey(val)) { return false; } list.add(val); map.put(val, list.size() - 1); return true; } public boolean remove(int val) { if (!map.containsKey(val)) { return false; } // 這裡刪除的時候,將最後一個元素和要刪的元素互換,然後刪除最後一個元素 int index = map.get(val); int last = list.get(list.size() - 1); list.set(index, last); list.remove(list.size() - 1); map.put(last, index); map.remove(val); return true; } public int getRandom() { return list.get(random.nextInt(list.size())); } }
方法二:用Set(不符合題意,題目要求O(1)的複雜度)
class RandomizedSet {
Set<Integer> set = null;
Random random = new Random();
public RandomizedSet() {
set = new HashSet<>();
}
public boolean insert(int val) {
return set.add(val);
}
public boolean remove(int val) {
return set.remove(val);
}
public int getRandom() {
return (int) set.toArray()[random.nextInt(set.size())];
}
}
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/insert-delete-getrandom-o1
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。