zoukankan      html  css  js  c++  java
  • Hash Table 的实现步骤是什么

    什么是HashTable

    Hash Table 是计算机科学中很重要的一种数据结构,其时间复杂度为O(1),主要是通过把关键字Key 映射到数组中的一个位置来访问记录,所以速度相当快。映射函数称为 Hash函数。

    Hash Table 的实现步骤是:

    1、创建一个固定大小的数组用于存放数据

    2、设计良好的 Hash 函数

    3、通过 Hash 函数把数据按照关键字 key 映射到数组中的某一个位置,并在此数据上进行数据存取

    下面是用PHP实现一个Hash Table

    class HashTable{
    // Container
    private $arrContainer;
    //size
    private $intSize = 10;
    /**
    * 构造函数
    */
    public function __construct(){
    $this->arrContainer= new SplFixedArray($this->intSize);
    }
    /**
    * hash 函数
    * @param str $strKey
    * @return number
    */
    private function hashFunc($strKey){
    $intLength = strlen($strKey);
    $intHashValue = 2881064151;
    for($index=0;$index<$intLength;$index++){
    $intHashValue+=ord($strKey{$index});
    }
    return $intHashValue % $this->intSize;
    }
    /**
    * 插入函数
    * @param str $strKey
    * @param str $strValue
    */
    public function insertIntoHashTable($strKey,$strValue){
    $intIndex = $this->hashFunc($strKey);
    $this->arrContainer[$intIndex]=$strValue;
    }
    /**
    * 查找函数
    * @param str $strKey
    */
    public function getFromHashTable($strKey){
    $intIndex = $this->hashFunc($strKey);
    return $this->arrContainer[$intIndex];
    }
    }
    //测试
    $hash = new HashTable();
    $hash->insertIntoHashTable('lkn','刘凯宁');
    $hash->insertIntoHashTable('lkn2','刘凯宁2');
    $hash->insertIntoHashTable('lkn3','刘凯宁3');
    $hash->insertIntoHashTable('lkn4','刘凯宁4');
    $hash->insertIntoHashTable('lkn5','刘凯宁5');
    echo $hash->getFromHashTable('lkn3');

  • 相关阅读:
    分享一些书籍,方方面面,很多值得一读
    C#网络爬虫--多线程处理强化版
    图书管理系统
    jquery完成界面无刷新加载登陆注册
    springboot jar项目 改为war项目
    nginx 配置文件配置(ssl和代理80端口)
    linux 安装mysql8.0
    linux redis安装和启动,远程链接
    linux nginx 安装启动
    linux tar方式安装配置jdk
  • 原文地址:https://www.cnblogs.com/cbryge/p/6134530.html
Copyright © 2011-2022 走看看