380. Insert Delete GetRandom O(1) | LeetCode | Top Interview 150 | 코딩 질문
발행: (2025년 12월 17일 오전 08:38 GMT+9)
1 min read
원문: Dev.to
Source: Dev.to
문제 링크
Insert Delete GetRandom O(1) – LeetCode
솔루션
class RandomizedSet {
ArrayList list;
HashMap map;
Random rand;
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
rand = new Random();
}
public boolean insert(int val) {
if (map.containsKey(val)) {
return false;
}
map.put(val, list.size());
list.add(val);
return true;
}
public boolean remove(int val) {
if (!map.containsKey(val)) {
return false;
}
int idx = map.get(val);
int lastVal = list.get(list.size() - 1);
list.set(idx, lastVal);
map.put(lastVal, idx);
list.remove(list.size() - 1);
map.remove(val);
return true;
}
public int getRandom() {
int idx = rand.nextInt(list.size());
return list.get(idx);
}
}
/**
* 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();
*/