zoukankan      html  css  js  c++  java
  • HashTable

    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)

  • 相关阅读:
    [BZOJ]2132: 圈地计划 最小割
    从最近MySQL的优化工作想到的
    Linux基本操作 9----- 认识与学习bash
    多路径配置vlome group共享存储,VG的更新。
    两位数乘法的速算方法(一)
    请对他有足够的重视——设计!
    ASP.NET中配置应用程序
    flex开发小技巧集锦
    刚制作完的SAP Sybase ASE15.7 [Sybase Central] 客户端
    Static 关键字的 5 种用法,你会几种?
  • 原文地址:https://www.cnblogs.com/xuyanran/p/8146979.html
Copyright © 2011-2022 走看看