[Leetcode] Insert Delete Getrandom O (1) Constant time inserts deletes and obtains random numbers

Source: Internet
Author: User

Design a data structure this supports all following operations in average O (1) time.

    1. insert(val): Inserts an item Val to the set if not already present.
    2. remove(val): Removes an item Val from the set if present.
    3. getRandom: Returns a random element from the current set of elements. Each element must has the same probability of being returned.

Example:

Init an empty set. Randomizedset randomset = new Randomizedset ();//inserts 1 to the set. Returns true as 1 was inserted successfully.randomSet.insert (1);//Returns false as 2 does not exist in the set.randomset. Remove (2);//inserts 2 to the set, returns True. Set now contains [1,2].randomset.insert (2);//getrandom should return either 1 or 2 randomly.randomSet.getRandom ();//Remo Ves 1 from the set, returns True. Set now contains [2].randomset.remove (1);//2 was already in the set, so return False.randomSet.insert (2);//Since 1 is th E only number in the set, Getrandom always return 1.randomset.getrandom ();

This problem allows us to insert delete and get random number operations in the constant time range, if there is no constant time limit, then it will be a very simple problem, we can directly use a set to do all the operation. However, due to time constraints, we can not achieve in the constant time to obtain random numbers, so only the alternative. The correct solution to this problem is to use a one-dimensional array and a hash table, where the array is used to hold the number, the hash table is used to establish the mapping between each number and its position in the array, for the insert operation, we first see whether the number has already existed in the hash table, if there is a direct return false, does not exist , we insert it at the end of the array and then establish a map of the number and its location. The delete operation is relatively tricky, we still have to determine whether it is in the hash table, if not, directly return false. Since the deletion of the hash table is constant time, and the array is not, in order to make the array deletion can also be a constant number of levels, we are actually going to delete the number and the last number of the array to replace the position, and then modify the corresponding hash table value, so we just need to delete the last element of the array to ensure that the constant time The return random number is simple for the array, so we just randomly generate a position and return the number at that location, see the code below:

classRandomizedset { 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. */    BOOLInsertintval) {        if(M.count (Val))return false;        Nums.push_back (Val); M[val]= Nums.size ()-1; return true; }        /** Removes a value from the set. Returns true if the set contained the specified element. */    BOOLRemoveintval) {        if(!m.count (Val))return false; intLast =Nums.back (); M[last]=M[val]; Nums[m[val]]=Last ;        Nums.pop_back ();        M.erase (Val); return true; }        /** Get a random element from the set.*/    intGetrandom () {returnNums[rand ()%nums.size ()]; }Private: Vector<int>Nums; Unordered_map<int,int>m;};

Resources:

Https://discuss.leetcode.com/topic/53286/ac-c-solution-unordered_map-vector

Leetcode all in one topic summary (continuous update ...)

[Leetcode] Insert Delete Getrandom O (1) Constant time inserts deletes and obtains random numbers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.