classRandomizedCollection { int n ;//当前集合大小 HashMap<Integer,Set<Integer>>map; ArrayList<Integer>list; Random random; /** Initialize your data structure here. */ publicRandomizedCollection() { this.random = newRandom(); this.map = newHashMap(); this.n = 0; this.list = newArrayList<>(); } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ publicbooleaninsert(int val) { Setset= map.get(val); if(set==null) set = newHashSet<>(); set.add(n);//添加索引 list.add(val); map.put(val, set); n++; return set.size()==1; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ publicbooleanremove(int val) { if(map.containsKey(val)){ intlastIndex= n-1;//得到最后2个值索引 Setlastset= map.get(list.get(lastIndex)); Setset= map.get(val); intcurrIndex= (int)set.iterator().next();//得到当前值索引 //进行删除操作 swap(list, currIndex, lastIndex); list.remove(n-1);//将其在列表中删除 set.remove(currIndex);//删除原值 if(set.size()==0) map.remove(val);//在图中删除 //修改最后一个值的索引 lastset.remove(n-1); lastset.add(currIndex); n--; }else{ returnfalse; } returntrue; } /** Get a random element from the collection. */ publicintgetRandom() { return list.get(random.nextInt(n)); } privatevoidswap(List<Integer> list ,int i,int j){ inttemp= list.get(i); list.set(i, list.get(j)); list.set(j, temp); } }