Java Solution with PriorityQueue in HashMap

  • 0

    I used PriorityQueue in HashMap to store information!

    class RandomizedCollection {
        /** Initialize your data structure here. */
        Random rnd;
        HashMap<Integer, PriorityQueue<Integer>> map;
        List<Integer> list;
        public RandomizedCollection() {
            list = new LinkedList<>();
            rnd = new Random();
            map = new HashMap<>();
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        public boolean insert(int val) {
            if(map.containsKey(val) && !map.get(val).isEmpty()) {
                return false;
                map.put(val, new PriorityQueue<>(1, (a, b)->, a)));
                return true;
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        public boolean remove(int val) {
            if(!map.containsKey(val) || map.get(val).isEmpty()) return false;
            int position = map.get(val).peek();
            int lastVal = list.get(list.size() - 1);
            list.set(position, lastVal);
            list.remove(list.size() - 1);
            return true;
        /** Get a random element from the collection. */
        public int getRandom() {
            return list.get(rnd.nextInt(list.size()));

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.