zoukankan      html  css  js  c++  java
  • Javascript实现HashTable类

    散列算法可以尽快在数据结构中找出指定的一个值,因为可以通过Hash算法求出值的所在位置,存储和插入的时候都按照Hash算法放到指定位置。

    <script>
    
    function HashTable() {
    	this.table = [];
    }
    
    //loselose散列函数
    HashTable.prototype.loseloseHash = function(str){
    	var hash = 0;
    	for(var i=0; i<str.length; i++){
    		hash += str.charCodeAt(i);
    	}
    	return hash;
    }
    
    //增加/更新 散列表
    HashTable.prototype.put = function(key,value){
    	this.table[this.loseloseHash(key)] = value;
    	return this.loseloseHash(key);
    }
    
    //删除散列表一个值
    HashTable.prototype.remove = function(key){
    	this.table[this.loseloseHash(key)] = undefined;
    }
    
    //获取散列表的一个值
    HashTable.prototype.get = function(key){
    	return this.table[this.loseloseHash(key)];
    }
    
    var hashtable = new HashTable();
    console.log(hashtable.put('Zhangsan','zhangsan@gmail.com')); //826
    console.log(hashtable.put('Jay','jay@foxmail.com')); //292
    console.log(hashtable.put('Ken','ken@126.com'));  //286
    console.log(hashtable.get('Jay')); //jay@foxmail.com
    hashtable.remove('Jay');
    console.log(hashtable.get('Jay')); //undefined
    </script>
    
  • 相关阅读:
    Hdu 1257 最少拦截系统
    Hdu 1404 Digital Deletions
    Hdu 1079 Calendar Game
    Hdu 1158 Employment Planning(DP)
    Hdu 1116 Play on Words
    Hdu 1258 Sum It Up
    Hdu 1175 连连看(DFS)
    Hdu 3635 Dragon Balls (并查集)
    Hdu 1829 A Bug's Life
    Hdu 1181 变形课
  • 原文地址:https://www.cnblogs.com/jaychan/p/5976429.html
Copyright © 2011-2022 走看看