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 ...
随机推荐
- python协程
http://bingotree.cn/?p=63 协程与yield的介绍,轻松搞笑. http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d ...
- IntelliJ IDEA License
http://jetbrains.tech/ http://jetbrains.tencent.click/
- CSS position relative absolute fixed
position属性absolute与relative 详解 最近一直在研究javascript脚本,熟悉DOM中CSS样式的各种定位属性,以前对这个属性不太了解,从网上找到两篇文章感觉讲得很透彻 ...
- 转帖:如何建立与使用 Window setup project
原文地址: http://www.codeproject.com/Articles/12548/Visual-Studio-Windows-Application-Setup-Project
- Remove Duplicate Letters I & II
Remove Duplicate Letters I Given a string which contains only lowercase letters, remove duplicate le ...
- hadoop MapReduce Yarn运行机制
原 Hadoop MapReduce 框架的问题 原hadoop的MapReduce框架图 从上图中可以清楚的看出原 MapReduce 程序的流程及设计思路: 首先用户程序 (JobClient) ...
- Semaphore(信号量)
Semaphore msdn介绍: 限制可同时访问某一资源或资源池的线程数. 命名空间: System.Threading 程序集: System(在 System.dll 中) 通俗理解: 1:宾馆 ...
- Cxgrid获取选中行列,排序规则,当前正在编辑的单元格内的值
Delphi Cxgrid获取选中行列,排序规则,当前正在编辑的单元格内的值 cxGrid1DBTableView1.Controller.FocusedRowIndex 当前行号 cxGrid1DB ...
- 2.js模式-单例模式
1. 单例模式 单例模式的核心是确保只有一个实例,并提供全局访问. function xx(name){}; Singleton.getInstance = (function(){ var inst ...
- Java for LeetCode 216 Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...