fixed: several bugs

This commit is contained in:
danielsss
2022-12-20 19:29:06 +11:00
parent 6eec01d594
commit bd21fd8be9
3 changed files with 77 additions and 20 deletions

View File

@@ -510,7 +510,7 @@ $$
=== "TypeScript"
```typescript title="array_hash_map.ts"
/* 键值对 int->String */
/* 键值对 Number -> String */
class Entry {
public key: number;
public val: string;
@@ -538,19 +538,23 @@ $$
public set(key: number, val: string | null) {
if (val !== null) {
this.elements[key] = new Entry(key, val);
} else {
this.elements[key] = null as any;
}
this.elements[key] = null as any;
}
/* 获取 */
public get(key: number): string {
return this.elements[key].val;
public get(key: number): string | null {
if (this.elements[key] instanceof Entry) {
return this.elements[key].val;
}
return null;
}
public entrySet() {
let arr = [];
let arr = [];
for (let i = 0; i < this.elements.length; i++) {
if (this.elements[i] !== null) {
if (this.elements[i]) {
arr.push(this.elements[i]);
}
}
@@ -560,7 +564,7 @@ $$
public valueSet() {
let arr = [];
for (let i = 0; i < this.elements.length; i++) {
if (this.elements[i] !== null) {
if (this.elements[i]) {
arr.push(this.elements[i].val);
}
}
@@ -570,13 +574,64 @@ $$
public keySet() {
let arr = [];
for (let i = 0; i < this.elements.length; i++) {
if (this.elements[i] !== null) {
if (this.elements[i]) {
arr.push(this.elements[i].key);
}
}
return arr;
}
}
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
// 初始化一个长度为 100 的桶(数组)
private bucket: ArrayList;
constructor() {
this.bucket = new ArrayList(100);
}
/* 哈希函数 */
private hashFunc(key: number): number {
return key % 100;
}
/* 查询操作 */
public get(key: number): string | null {
let index = this.hashFunc(key);
let val = this.bucket.get(index);
if (val === null) return null;
return val;
}
/* 添加操作 */
public put(key: number, val: string) {
let index = this.hashFunc(key);
this.bucket.set(index, val);
}
/* 删除操作 */
public remove(key: number) {
let index = this.hashFunc(key);
// 置为 null ,代表删除
this.bucket.set(index, null);
}
/* 获取所有键值对 */
public entrySet(): Entry[] {
return this.bucket.entrySet();
}
/* 获取所有键 */
public keySet(): number[] {
return this.bucket.keySet();
}
/* 获取所有值 */
public valueSet(): string[] {
return this.bucket.valueSet();
}
}
```
=== "C"