Only a Hash Set is enough?


  • -1
    S

    class RandomizedSet {
    public:
    set<int>s;
    /** Initialize your data structure here. */
    RandomizedSet() {

    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        bool existed = true;
        if (s.find(val) != s.end()) {
            existed = false;
        }
        else {
            s.insert(val);
        }
        return existed;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        bool existed = false;
        if (s.find(val) != s.end()) {
            existed = true;
            s.erase(val);
        }
        return existed;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        auto iter = s.begin();
        advance(iter, rand() % s.size());
        return *iter;
    }
    

    };

    /**

    • Your RandomizedSet object will be instantiated and called as such:
    • RandomizedSet obj = new RandomizedSet();
    • bool param_1 = obj.insert(val);
    • bool param_2 = obj.remove(val);
    • int param_3 = obj.getRandom();
      */

  • 2
    C

    Hi, if the underlaying structure for set is red-black tree, then insert, remove and advance will be O(logN). if the underlaying structure is hash based, then insert and remove are O(1) but advance will be much more expensive (I think it is O(n)


  • 0
    C

    @sidawang don't think advance() is O(1)


Log in to reply
 

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