SimpleHashTable
简单的Hash Table 实现,下次被问到,至少不是从0开始。不过笔试问这个毕竟不多。
public struct Item<K, V>
{
public K Key { get; set; }
public V Value { get; set; }
}
public class SimpleHashTable<K, V>
{
private int _size;
private LinkedList<Item<K, V>>[] _items;
public SimpleHashTable(int size)
{
this._size = size;
_items = new LinkedList<Item<K, V>>[_size];
}
public void Add(K key, V value)
{
var item = Find(key);
if (item == null)
{
var list = FindListByKey(key);
list.AddLast(new Item<K, V>()
{
Key = key,
Value = value
});
}
else
{
throw new Exception("The item is already exist.");
}
}
public V Find(K key)
{
var list = FindListByKey(key);
foreach (var item in list)
{
if (item.Key.Equals(key))
{
return item.Value;
}
}
return default(V);
}
public void Remove(K key)
{
var list = FindListByKey(key);
var item = list.Where(a => a.Key.Equals(key)).FirstOrDefault();
if (!item.Equals(default(Item<K, V>)))
{
list.Remove(item);
}
}
private LinkedList<Item<K, V>> FindListByKey(K key)
{
var hash = key.GetHashCode();
var index = Math.Abs(hash % _size);
if (_items[index] == null)
{
_items[index] = new LinkedList<Item<K, V>>();
}
return _items[index];
}
}
SimpleHashTable的更多相关文章
- .NET 2.0 参考源码索引
http://www.projky.com/dotnet/2.0/Microsoft/CSharp/csharpcodeprovider.cs.htmlhttp://www.projky.com/do ...
随机推荐
- __getattr__ 与动态属性
直接上代码 >>> class Test(object): ... def __getattr__(self,attr_name): ... setattr(self, attr_n ...
- Strobogrammatic Number
Strobogrammatic Number I A strobogrammatic number is a number that looks the same when rotated 180 d ...
- Semantic-UI-React (称 stardust) 对比 Antd
Semantic-UI-React: http://react.semantic-ui.com/ ANTD :http://ant.design/ Amaze UI React: http://ama ...
- c++数据类型和定义
我们都知道,刚开始学习数学的时候.乘法口诀.99乘法口诀.这个是大家都需要背的.背熟了这个,大家才能知道遇到算术题如何计算.这个99乘法口诀就是一种定义. 同样任何的语言都会有很多的定义.比如语文:各 ...
- ACM/ICPC 之 用双向链表 or 模拟栈 解“栈混洗”问题-火车调度(TSH OJ - Train)
本篇用双向链表和模拟栈混洗过程两种解答方式具体解答“栈混洗”的应用问题 有关栈混洗的定义和解释在此篇:手记-栈与队列相关 列车调度(Train) 描述 某列车调度站的铁道联接结构如Figure 1所示 ...
- ffmpeg-20160726-bin.7z
ESC 退出 0 进度条开关 1 屏幕原始大小 2 屏幕1/2大小 3 屏幕1/3大小 4 屏幕1/4大小 S 下一帧 [ -2秒 ] +2秒 ; -1秒 ' +1秒 下一个帧 -> -5秒 f ...
- ABAP 仓库理货单导出
*&---------------------------------------------------------------------* *& Report *& ...
- 用基础动画实现iOS控件循环旋转
- (void)viewDidLoad { [super viewDidLoad]; UIButton* ag=[[UIButton alloc]initWithFrame:CGRectMake(sc ...
- Effective C++ -----条款25:考虑写出一个不抛异常的swap函数
当std::swap对你的类型效率不高时,提供一个swap成员函数,并确定这个函数不抛出异常. 如果你提供一个member swap,也该提供一个non-member swap用来调用前者.对于cla ...
- VC++ LoadLibrary失败,错误126(找不到指定的模块)
在VS中调用一个资源模块dll,LoadLibrary返回值为NULL,没有加载成功.GetLastError后原因为"找不到指定的模块"!代码如下: HINSTANCE hIns ...