Why does my code give correct result, but get a runtime error?


  • 0
    S

    This is my code:

    class RandomizedCollection {
    private:
        unordered_map<int, priority_queue<int>> m;
        vector<int> v;
    public:
        /** Initialize your data structure here. */
        RandomizedCollection() {
            
        }
        
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        bool insert(int val) {
            v.push_back(val);
            m[val].push(v.size() - 1);
            return m[val].size() == 1;
        }
        
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        bool remove(int val) {
            if(m.find(val) == m.end() || m[val].size() == 0) {
                return false;
            }
            int index1 = m[val].top(), index2 = v.size() - 1;
            v[index1] = v[index2];
            v.pop_back();
            m[val].pop();
            m[v[index1]].pop();
            m[v[index1]].push(index1);
            return true;
        }
        
        /** Get a random element from the collection. */
        int getRandom() {
            int answer = v[rand() % v.size()];
            return answer;
        }
    };
    

  • 0
    L
    This post is deleted!

Log in to reply
 

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