Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 122 期(数据结构-哈希):哈希表 #125

Open
wingmeng opened this issue Oct 11, 2019 · 0 comments
Open

第 122 期(数据结构-哈希):哈希表 #125

wingmeng opened this issue Oct 11, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

哈希表(Hash Table),又叫散列表,是一种用于存储键值对(key value pair)的数据结构,因为 Hash Table 根据key 查询 value 的速度很快,所以它常用于实现 Map、Dictinary、Object 等数据结构。

一个Hash Table通常具有下列方法:

  • add:增加一组键值对
  • remove:删除一组键值对
  • lookup:查找一个键对应的值

哈希表的简易实现:

function hash(string, max) {
  var hash = 0;
  for (var i = 0; i < string.length; i++) {
    hash += string.charCodeAt(i);
  }
  return hash % max;
}


function HashTable() {
  let storage = [];
  const storageLimit = 4;


  this.add = function (key, value) {
    var index = hash(key, storageLimit);
    if (storage[index] === undefined) {
      storage[index] = [
        [key, value]
      ];
    } else {
      var inserted = false;
      for (var i = 0; i < storage[index].length; i++) {
        if (storage[index][i][0] === key) {
          storage[index][i][1] = value;
          inserted = true;
        }
      }
      if (inserted === false) {
        storage[index].push([key, value]);
      }
    }
  }


  this.remove = function (key) {
    var index = hash(key, storageLimit);
    if (storage[index].length === 1 && storage[index][0][0] === key) {
      delete storage[index];
    } else {
      for (var i = 0; i < storage[index]; i++) {
        if (storage[index][i][0] === key) {
          delete storage[index][i];
        }
      }
    }
  }


  this.lookup = function (key) {
    var index = hash(key, storageLimit);
    if (storage[index] === undefined) {
      return undefined;
    } else {
      for (var i = 0; i < storage[index].length; i++) {
        if (storage[index][i][0] === key) {
          return storage[index][i][1];
        }
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant