|
| 1 | +/* ============================================================================== |
| 2 | + * 功能描述:IDG |
| 3 | + * 创 建 者:gz |
| 4 | + * 创建日期:2017/5/10 12:41:14 |
| 5 | + * ==============================================================================*/ |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Data.SqlTypes; |
| 9 | +using System.Linq; |
| 10 | +using System.Text; |
| 11 | +using System.Threading; |
| 12 | + |
| 13 | +namespace IDGSln |
| 14 | +{ |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// IDG |
| 18 | + /// </summary> |
| 19 | + public class RandomizedSet |
| 20 | + { |
| 21 | + //insert remove getRandom |
| 22 | + private Dictionary<int, int> _dict; //key: value, Value: index |
| 23 | + private List<int> _valList; //element of value list, for it can get the O(1) visit |
| 24 | + public RandomizedSet() |
| 25 | + { |
| 26 | + _dict = new Dictionary<int, int>(); |
| 27 | + _valList = new List<int>(); |
| 28 | + } |
| 29 | + |
| 30 | + public bool Insert(int val) |
| 31 | + { |
| 32 | + if (!_dict.ContainsKey(val)) |
| 33 | + { |
| 34 | + _dict.Add(val, _valList.Count); |
| 35 | + _valList.Add(val); |
| 36 | + return true; |
| 37 | + } |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + public bool Remove(int val) |
| 42 | + { |
| 43 | + if (!_dict.ContainsKey(val)) return false; |
| 44 | + int removeIndex = _dict[val]; //_dict.Values: element index collection |
| 45 | + |
| 46 | + swapToLast(removeIndex); |
| 47 | + |
| 48 | + _valList.Remove(val); |
| 49 | + _dict.Remove(val); |
| 50 | + return true; |
| 51 | + } |
| 52 | + |
| 53 | + //i-待移除元素的索引 |
| 54 | + //将待移除元素移到_valList的末尾,修改原来末尾元素在字典中的键值 |
| 55 | + private void swapToLast(int i) |
| 56 | + { |
| 57 | + int lastIndex = _valList.Count - 1; |
| 58 | + if (i > lastIndex) return; |
| 59 | + int lastVal = _valList[lastIndex]; |
| 60 | + int tmpVal = _valList[i]; |
| 61 | + _valList[i] = lastVal; // the key is to prove " i < lastIndex" !!! |
| 62 | + _valList[lastIndex] = tmpVal; |
| 63 | + //this is important, to update the last index value in dictionary |
| 64 | + _dict[lastVal] = i; |
| 65 | + } |
| 66 | + |
| 67 | + public int GetRandom() |
| 68 | + { |
| 69 | + long tick = DateTime.Now.Ticks; |
| 70 | + Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32)); |
| 71 | + int randnum = ran.Next(_valList.Count); |
| 72 | + if (_valList.Count == 0) return -1; |
| 73 | + Thread.Sleep(20); |
| 74 | + |
| 75 | + return _valList[randnum]; |
| 76 | + } |
| 77 | + |
| 78 | + } |
| 79 | + |
| 80 | +} |
0 commit comments