HashTable 主要包含

  1. Hash(string key), 先计算hash后计算余数, 对于string而言,把每一位char的ASCII码叠加起来。  sum = sum*37 + char[i], sum%data.length, 要考虑负余数的情况
  2. Insert(string key), 调用hash()拿到index, 存值至bucket
  3. Delete(string key), 调用hash()拿到index,去值from bucket

扩展:

  C# 中的HashTable Class 用的是相同的思想,第一级是数组 data【Size】, 每一元素类型是ArrayList<Bucket>

  Bucket is a custom class, it contains Key, Value properties.

代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestCase1.TestCase
{
    /// <summary>
    /// int Hash(string value)
    /// Insert(string value)
    /// Delete(string value)
    /// </summary>
    public class CustomHashTable
    {
        private ArrayList[] data = new ArrayList[101];

        public CustomHashTable()
        {
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = new ArrayList(4);
            }
        }

        private int ComputeHash(string s)
        {
            char[] chas = s.ToCharArray();
            int sum = 0;
            for (int i = 0; i < chas.Length; i++)
            {
                sum += sum * 37 + (int)chas[i];
            }

            int tot = sum % this.data.Length;
            if (tot < 0)
            {
                tot = tot + this.data.Length;
            }

            return tot;
        }

        public void Insert(string s)
        {
            int index = ComputeHash(s);
            if (!this.data[index].Contains(s))
            {
                this.data[index].Add(s);
            }            
        }

        public void Delete(string s)
        {
            int index = ComputeHash(s);
            if (this.data[index].Contains(s))
            {
                this.data[index].Remove(s);
            }
        }        
    }
}

 总结

HashTable is a data structure that stores key value pair.  Insert is O(1), Delete is O(1), Get is O(1)

posted on 2017-12-30 01:11  xuyanran  阅读(135)  评论(0编辑  收藏  举报