706.设计哈希映射

2020-04-08
设计哈希映射
不使用任何内建的哈希表库设计一个哈希集合 具体地说,你的设计应该包含以下的功能
  • put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
  • get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。
  • remove(key):如果映射中存在这个键,删除这个数值对。

题解:
思路1: 使用对象设计哈希集合
/**
 * Initialize your data structure here.
 */
var MyHashMap = function () {
  this.hashContent = {}; // 使用对象模拟hash表
};
MyHashMap.prototype.put = function (key, value) {
  this.hashContent[key] = value; // 没有值则赋值 有值则覆盖
};
MyHashMap.prototype.get = function (key) {
  // 用hasOwnProperty是因为 如果key的val就是undefined 那么用if就无法判断这个key到底存不存在
  if (this.hashContent.hasOwnProperty(key)) return this.hashContent[key];
  // 也可以用if(key in this.hashContent)
  // if (key in this.hashContent) return this.hashContent[key];
  return -1;
};
MyHashMap.prototype.remove = function (key) {
  if (this.hashContent.hasOwnProperty(key)) delete this.hashContent[key];
};

 

 
posted @ 2020-04-08 08:56  蓝小胖纸  阅读(184)  评论(0编辑  收藏  举报