码迷,mamicode.com
首页 > 其他好文 > 详细

380. Insert Delete GetRandom O(1)

时间:2017-10-16 19:48:07      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:operation   res   span   结构   asto   复杂   str   design   follow   

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(1)

标签:operation   res   span   结构   asto   复杂   str   design   follow   

原文地址:http://www.cnblogs.com/wzj4858/p/7677994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!