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)

  • 相关阅读:
    mysql把查询结果集插入到表理
    js遍历json数据
    php事务回滚
    win10定时执行php脚本
    php输出json的内容
    图像的几个基本概念
    linux系统编程之I/O内核数据结构
    linux系统编程之错误处理
    深拷贝和浅拷贝
    mysql用户的创建
  • 原文地址:https://www.cnblogs.com/xuyanran/p/8146979.html
Copyright © 2011-2022 走看看