Insert Delete GetRandom O(1)
public class RandomizedSet {
ArrayList<Integer> nums;
HashMap<Integer, Integer> nums2Int;
Random rand;
public RandomizedSet() {
nums = new ArrayList<>();
nums2Int = new HashMap<>();
rand = new Random();// do intialization if necessary
}
/*
* @param val: a value to the set
* @return: true if the set did not already contain the specified element or false
*/
public boolean insert(int val) {
if(nums.contains(val)){
return false;
}
nums2Int.put(val,nums.size());
nums.add(val);
return true;
}
/*
* @param val: a value from the set
* @return: true if the set contained the specified element or false
*/
public boolean remove(int val) {
if(nums2Int.containsKey(val) == false){
return false;
}
int index = nums2Int.get(val);
if(index < nums.size() - 1){
int last = nums.get(nums.size()-1);
nums2Int.put(last, index);
nums.set(index , last);
}
nums2Int.remove(nums.size() - 1);
nums.remove(nums.size() - 1);
return true;
}
/*
* @return: Get a random element from the set
*/
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));// write your code here
}
}
最后更新于
这有帮助吗?