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)

  • 相关阅读:
    flexlm破解入门文献列表
    【分享】SRIO错误的基本判决
    LDO功耗计算
    CT128M4SSD1升级固件3种方法方法
    SYSBIOS中malloc和Memory_alloc的区别.doc
    VID = 058F PID = 6387 可用的量产工具
    Debian 6 nvidia显卡驱动安装
    Java Volatile的双重含义
    Windows下PHP使用Apache的mod_fcgid模块安装及配置
    Flask之基于route装饰器的路由系统(源码阅读解析)
  • 原文地址:https://www.cnblogs.com/xuyanran/p/8146979.html
Copyright © 2011-2022 走看看