|
| 1 | + |
| 2 | +// 另一种解决冲突的方法是线性探查。当想向表中某个位置加入一个新元素的时候,如果索引 |
| 3 | +// 为index的位置已经被占据了,就尝试index + 1的位置。如果index + 1的位置也被占据了,就尝试 |
| 4 | +// index + 2的位置, |
| 5 | + |
| 6 | +function HashTable() { |
| 7 | + this.table = [] |
| 8 | +} |
| 9 | +let ValuePair = function (key, value) { |
| 10 | + this.key = key |
| 11 | + this.value = value |
| 12 | + this.toString = function () { |
| 13 | + return '[' + this.key + ' - ' + this.value + ']'; |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +var LoseLoseHashCode = function (key) { |
| 18 | + // 根据这个key字符的ascii码的和得到一个数字 |
| 19 | + var hash = 0; |
| 20 | + for (let i = 0; i < key.length; i++) { |
| 21 | + hash += key.charCodeAt(i) |
| 22 | + } |
| 23 | + return hash % 37 |
| 24 | +} |
| 25 | + |
| 26 | +// 重写put方法 |
| 27 | +HashTable.prototype.put = function (key, value) { |
| 28 | + var postition = LoseLoseHashCode(key) |
| 29 | + if (this.table[postition] != undefined) { |
| 30 | + this.table[postition] = value |
| 31 | + } else { |
| 32 | + // 2 也就是有位置了 需要先加1 |
| 33 | + let index = postition++ |
| 34 | + while (this.table[index] != undefined) { |
| 35 | + index++ |
| 36 | + } |
| 37 | + this.table[postition] = new ValuePair(key, value) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// 重写get方法 |
| 42 | +HashTable.prototype.get = function (key) { |
| 43 | + let pos = LoseLoseHashCode(key) |
| 44 | + if (this.table[pos].key == key) { |
| 45 | + return this.table[pos].value |
| 46 | + } else { |
| 47 | + let index = pos++ |
| 48 | + while (this.table[pos] != undefined && this.table[pos].key != key) { |
| 49 | + index++ |
| 50 | + } |
| 51 | + if (this.table[index].key == key) { |
| 52 | + return this.table[index].value |
| 53 | + } |
| 54 | + } |
| 55 | + return undefined |
| 56 | +} |
| 57 | + |
| 58 | +// 重写remove方法 |
| 59 | +HashTable.prototype.remove = function (key) { |
| 60 | + let pos = LoseLoseHashCode(key) |
| 61 | + if (this.table[pos].key == key) { |
| 62 | + this.table[pos] = undefined |
| 63 | + return true |
| 64 | + } else { |
| 65 | + let index = pos++ |
| 66 | + while (this.table[pos] != undefined && this.table[pos].key != key) { |
| 67 | + index++ |
| 68 | + } |
| 69 | + if (this.table[index].key == key) { |
| 70 | + this.table[pos] = undefined |
| 71 | + return true |
| 72 | + } |
| 73 | + } |
| 74 | + return false |
| 75 | +} |
| 76 | + |
0 commit comments