Leetcode-insert Delete getrandom O (1)

Source: Internet
Author: User

Design a data structure this supports all following operations in 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 ();
Analysis:for O (1) Insert and remove, we need HashMap. For O (1) The random access, we need to arrange all elements in an array. To perform insert and remove for a array in O (1), we can swap the deleted element with the last element and decrease the   List end. Solution:
1 ImportJava.util.Random;2 3  Public classRandomizedset {4Hashmap<integer,integer>map;5List<integer>list;6     intListend;7 8     /**Initialize your data structure here.*/9      PublicRandomizedset () {TenMap =NewHashmap<integer,integer>(); OneList =NewArraylist<integer>(); AListend = 0; -     } -      the     /**inserts a value to the set. Returns true if the set did not already contain the specified element. */ -      Public BooleanInsertintval) { -         if(Map.containskey (Val))return false; -          + Map.put (val,listend); -         if(Listend = =list.size ()) { + List.add (val); A}Else { at List.set (listend,val); -         } -listend++; -         return true; -     } -      in     /**removes a value from the set. Returns true if the set contained the specified element. */ -      Public BooleanRemoveintval) { to         if(Map.isempty () | |!map.containskey (val))return false; +          -         //to remove a element, we swap it with the last element and decrease the index. the         intindex =Map.get (val); *         intLastval = List.get (--listend); $ List.set (index,lastval);Panax NotoginsengMap.put (Lastval,index);//remeber to update the last element's index in HASHMAP. -          the         //Note:this must was performed after swap, because if the removed element was the last element, perform the following EA Rlier would leave the HashMap, which may block inserting the same element later and create a async between HashMap and List . + Map.Remove (val); A         return true; the     } +      -     /**Get a random element from the set.*/ $      Public intGetrandom () { $Random engine =NewRandom (); -         intindex =Engine.nextint (listend); -         returnList.get (index); the     } - }Wuyi  the /** - * Your Randomizedset object would be instantiated and called as such: Wu * Randomizedset obj = new Randomizedset (); - * Boolean param_1 = Obj.insert (val); About * Boolean param_2 = Obj.remove (val); $ * int param_3 = Obj.getrandom (); -  */

Leetcode-insert Delete getrandom O (1)

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.