Map<Integer, Set<Integer>> map; List<Integer> nums; /** Initialize your data structure here. */ publicRandomizedCollection(){ map = new HashMap<Integer, Set<Integer>>(); nums = new ArrayList<Integer>(); } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ publicbooleaninsert(int val){ //将 val 添加到数组中 nums.add(val); //将 当前下标添加进 val 对应的 set Set<Integer> set = map.getOrDefault(val, new HashSet<Integer>()); set.add(nums.size() - 1); //将 set 放入 map map.put(val, set); //数组中是否已经存在 val return set.size() == 1; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ publicbooleanremove(int val){ //数组中没有 val,删除失败 if(!map.containsKey(val)){ returnfalse; } //得到 val 对应的一个 数组下标 Iterator<Integer> it = map.get(val).iterator(); int i = it.next(); //得到数组中最后一个数字 int lastNum = nums.get(nums.size() - 1); //将最后一个数组拷贝到下标 i 处 nums.set(i, lastNum); //删除set 中的下标 map.get(val).remove(i); map.get(lastNum).remove(nums.size() - 1); //将 lastNum 的新下标加入set if(i < nums.size() - 1){ map.get(lastNum).add(i); } //删除后 set 为空,删除这个 键值对 if(map.get(val).size() == 0){ map.remove(val); } //删除数组中最后一个元素 nums.remove(nums.size() - 1); returntrue; } /** Get a random element from the collection. */ publicintgetRandom(){ //随机生成数组下标 return nums.get( (int) ( Math.random() * nums.size() ) ); } }