380 - Insert Delete GetRandom O(1)

解法一 - Hash Table + Array

這題是擴展眼界題,邊聽影片邊做,可以看:https://www.youtube.com/watch?v=y240Qh9H9uk

class RandomizedSet {
public:
    /** 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) {
        // If the value is inside m_, return false
        if(m_.count(val)) { return false; }

        // If not exist, append to the back of array and record in the m_
        m_[val] = vals_.size();
        vals_.push_back(val);
        return true;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        // If the value is not inside m_, return false
        if(!m_.count(val)) { return false; }

        // If exist, append to the back of array and remove from m_
        int index = m_[val];
        m_[vals_.back()] = index;
        m_.erase(val);
        swap(vals_[index], vals_.back());
        vals_.pop_back();
        return true;
    }

    /** Get a random element from the set. */
    int getRandom() {
        int index = rand() % vals_.size();
        return vals_[index];
    }

private:
    unordered_map<int, int> m_; // stores value and array index
    vector<int> vals_; // stores the value for getRandom
};

/**
 * 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();
 */

results matching ""

    No results matching ""