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

Design a key value data structure support Get/Fetch/Delete/RandomDelete all in O(1)

时间:2017-12-13 11:32:49      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:his   value   struct   port   move   store   over   except   imp   

 1 Implement a Key-Value pair datastucture such that there is:
 2     O(1) insertion                    void insert(K, V)
 3     O(1) fetching                     
 4     O(1) deletion                    
 5     O(1) fetching of Random element  
 6     
 7     
 8     
 9 Test cases:
10 1. Unit tests to cover all APIs
11 2. We try delete a key not exist, 
12 3. Performance test case to verify its O(1)  
13 4. Track memory
14 5. 
15     
16 public class KeyValueStore
17 {
18     private Dictionary<string, int> dict = new Dictionary<string, int>();
19     private Tuple<string, SomeType> [] array = new Tuple<string, SomeType>[1000]; 
20     private int current = 0;
21      
22     public void Insert(string key, SomeType value)
23     {
24         if (!dict.ContainsKey(key))
25         {
26             this.array[current] = new Tuple<string, SomeType>(key, value);
27             dict[key] = current;
28             current++;
29         }
30         else
31         {
32             this.array[dict[key]] = new Tuple<string, SomeType>(key, value);
33         }
34     }
35     
36     public SomeType Fetch(string key)
37     {
38         if (!dict.ContainsKey(key))
39         {
40             throw new KeyNotFoundException(key);
41         }
42         else
43         {
44             return this.array[dict[key]].Item2;
45         }
46     }
47     
48     public void Delete(string key)
49     {
50         if (dict.ContainsKey(key))
51         {
52             int toRemoveIndex = dict[key];
53             int lastElementIndex = this.current - 1;
54             
55             // swap last element with the element to remove
56             this.array[toRemoveIndex] = this.array[lastElementIndex];
57             dict.Remove(key);
58             
59             // we need to update the dict for the last element
60             string key = this.array[lastElementIndex].Item1;
61             dict[key] = toRemoveIndex;
62             this.current--;
63         }
64     }
65     
66     public SomeType FetchRandom()
67     {
68         if (current == 0)
69         {
70             throw new ValueNotFoundException();
71         }
72         else
73         {
74             int random = Random(0, current);
75             return this.array[random].Item2;
76         }
77     }
78 }

 

Design a key value data structure support Get/Fetch/Delete/RandomDelete all in O(1)

标签:his   value   struct   port   move   store   over   except   imp   

原文地址:http://www.cnblogs.com/liangmou/p/8031097.html

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