380. Insert Delete GetRandom O

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了380. Insert Delete GetRandom O相关的知识,希望对你有一定的参考价值。

Design a data structure that 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 current set of elements. Each element must have the same probability of being returned.

设计一个数据结构,使得插入、删除,随机获取一个元素的时间复杂度都是O(1) 

 
 1 class RandomizedSet {
 2 
 3     ArrayList<Integer> nums;
 4     HashMap<Integer, Integer> locs;
 5     java.util.Random rand = new java.util.Random();
 6     /** Initialize your data structure here. */
 7     public RandomizedSet() {
 8         nums = new ArrayList<Integer>();
 9         locs = new HashMap<Integer, Integer>();
10     }
11     
12     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
13     public boolean insert(int val) {
14         boolean contain = locs.containsKey(val);
15         if ( contain ) return false;
16         locs.put( val, nums.size());
17         nums.add(val);
18         return true;
19     }
20     
21     /** Removes a value from the set. Returns true if the set contained the specified element. */
22     public boolean remove(int val) {
23         boolean contain = locs.containsKey(val);
24         if ( ! contain ) return false;
25         int loc = locs.get(val);
26         if (loc < nums.size() - 1 ) { // not the last one than swap the last one with this val
27             int lastone = nums.get(nums.size() - 1 );
28             nums.set( loc , lastone );//将最后一个位置的元素拷贝到本位置,达到覆盖被删除元素的目的
29             locs.put(lastone, loc); //因为map中最后一个位置的元素被移走了,所以要同步修改mamp中的位置索引
30         }
31         locs.remove(val); //删除map中要被删除元素
32         nums.remove(nums.size() - 1);//删除list中最后一个元素
33         return true;
34     }
35     
36     /** Get a random element from the set. */
37     public int getRandom() {
38         return nums.get( rand.nextInt(nums.size()) );
39     }
40 }

 



以上是关于380. Insert Delete GetRandom O的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 380. Insert Delete GetRandom O

380 Insert Delete GetRandom O

380. Insert Delete GetRandom O

LeetCode 380. Insert Delete GetRandom O

[leetcode] 380. Insert Delete GetRandom O

380. Insert Delete GetRandom O