zoukankan      html  css  js  c++  java
  • php实现hashTable

    Hash表作为最重要的数据结构之一,也叫做散列表。使用PHP实现Hash表的功能。PHP可以模拟实现Hash表的增删改查。通过对key的映射到数组中的一个位置来访问。映射函数叫做Hash函数,存放记录的数组称为Hash表。

    Hash函数把任意长度的和类型的key转换成固定长度输出。不同的key可能拥有相同的hash。
    Hash表的时间复杂度为O(1)

    class HashTable{
      	private $arr = array();
      	private $size=10;
      	public function __construct(){
      		$this->arr = new  SplFixedArray($this->size);
      	}
      	public function SimpleHash($key){
      		$len = strlen($key);
      		$ascTotal=0;
      		for($i=0;$i<$len;$i++){
      			$ascTotal+=ord($key[$i]);
      		}
      		return $ascTotal%$this->size;
      	}
      	//添加
      	public function set($key,$value){
      		$hash = $this->SimpleHash($key);
      		$this->arr[$hash]=$value;
      		return true;
      	}
      	//获取
      	public function get($key){
      		$hash = $this->SimpleHash($key);
      		return $this->arr[$hash];
      	}
      	//获取列表
      	public function getList(){
      		print_r($this->arr);
      	}
      	//修改hash大小
      	public function editSize($size){
      		$this->size = $size;
      		$this->arr->setSize($size);
      	}
      } 
      $objtable = new HashTable();
      $objtable->set("test",40);
      $objtable->set('a',10);
      $objtable->editSize(40);
    

      

  • 相关阅读:
    XXX is not in the sudoers file
    git错误“无法推送一些引用到xxx"的解决方法
    mysql开启远程访问
    ubuntu 在启动器中启动webstorm和phpstorm
    ubuntu nginx卸载和安装
    基于grunt构建的前端集成开发环境
    fullPage.js
    常见的HTTP状态码
    JS随机数
    CSS3简单的动画
  • 原文地址:https://www.cnblogs.com/zh718594493/p/12093830.html
Copyright © 2011-2022 走看看