简单易懂的TypeScript哈希表教程

用TypeScript写个哈希表——说白了就是“找东西利器” 哈希表这个东西呢,跟生活中找钥匙差不多。想象一下,你每次出门都乱丢钥匙,回家要用半小时才能找到它。如果有个哈希表,那你一秒就能知道钥匙放哪了。所以今天我们来用TypeScript写个哈希表,别担心,跟朋友聊天一样简单。 什么是哈希表? 哈希表就像给你的钥匙分配了个专属抽屉,你把钥匙往哈希表里一丢,它自己找个抽屉放好,等你要用的时候,你直接问它:“我的钥匙在哪呢?” 它马上告诉你在哪个抽屉里,秒找。是不是很方便?那咱现在就来动手写一个。 代码部分——慢慢来,不急 我们来一步步写哈希表,代码都标注好,解释清楚,放心不会扯得太远。 class HashTable<T> { // 创建一个桶数组,桶就是个小抽屉,里面装着key-value对 private buckets: Array<Array<[string, T]>>; // 哈希表的大小,也就是有多少个抽屉 private size: number; constructor(size: number) { this.size = size; // 创建一个指定大小的桶数组,初始每个位置是个空数组 this.buckets = new Array(size).fill(null).map(() => []); // 为啥要fill(null)?TypeScript不允许你直接在空数组上map,得先填充一波。 } // 哈希函数,负责把key变成数字,这样才能找到对应的桶 private hash(key: string): number { let hash = 0; for (let i = 0; i […]

Read More

448. Find All Numbers Disappeared in an Array

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. Example 1: Input: nums = [4,3,2,7,8,2,3,1] Output: [5,6] Example 2: Input: nums = [1,1] Output: [2] Constraints: n == nums.length 1 <= […]

Read More

Check If N and Its Double Exist

Given an array arr of integers, check if there exist two indices i and j such that: i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j] Example 1: Input: arr = [10,2,5,3] Output: true Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 […]

Read More

3. Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = “abcabcbb” Output: 3 Explanation: The answer is “abc”, with the length of 3. Example 2: Input: s = “bbbbb” Output: 1 Explanation: The answer is “b”, with the length of 1. Example 3: Input: s = […]

Read More