思路
insert 其实用得到search,remove也是,当时o(1)想到的是hash set,但是对于random取,随机数相当于获得的是index,根据index获取元素 Set 数据结构不符合。
随机获取应该是数组,但是数组搜索和删除不是o(1)
最后的思路是 用hash和数组存,对于数组删除,可以使用交换的方式

 
 通过交换的方式进行删除。
代码
class RandomizedSet {
    private HashMap<Integer, Integer> hashMap;
    private List<Integer> list ;
    Random random = new Random();
    public RandomizedSet() {
        hashMap = new HashMap<>();
        list = new ArrayList<>();
    }
    public boolean insert(int val) {
       if (hashMap.containsKey(val)){
           return false;
       }
       int size = list.size();
       hashMap.put(val,size);
       list.add(val);
       return true;
    }
    public boolean remove(int val) {
        if (hashMap.containsKey(val)){
            int index = hashMap.get(val);
            int lastElement = list.get(list.size() - 1);
            list.set(index, lastElement);//index 放的是最后一个值
            list.remove(list.size() - 1);//把最后一个删除是o(1)
            hashMap.put(lastElement, index); // 更新最后一个元素在 hashMap 中的位置
            hashMap.remove(val);
            return true;
        }
        return false;
    }
    public int getRandom() {
        int i = random.nextInt(list.size());
        return list.get(i);
    }
}
/**
 * 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();
 */
遇到问题
Java 8在线文档
 https://docs.oracle.com/javase/8/docs/api/?xd_co_f=47c934d9-e663-4eba-819c-b726fc2d0847
 Java 22在线文档
 https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/ArrayList.html#removeLast()
代码报错,是因为我使用了removeList,这个功能是Java jdk21以后才有的,我刚开始写代码用的jdk22,所以有这个提示,但是当我用Java 8 运行时,报错
 




















