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');

  • 相关阅读:
    Jmeter关联-获取token值
    Jmeter接口测试
    Jmeter关联,正则表达式提取器使用2
    Jmeter关联,正则表达式提取器使用1
    Jmeter-CSV Data Set Config参数化
    Fiddler基本用法:手机抓包1
    接口测试该怎样入手?
    Fiddler简介与Web抓包,远程抓包(IE、360、谷歌、火狐)
    PHP 插件资源
    利用PHP递归 获取所有的上级栏目
  • 原文地址:https://www.cnblogs.com/cbryge/p/6134530.html
Copyright © 2011-2022 走看看