2.3 Hash & Heap

Hash

• 原理:

Key, value, storage

Hash Table / multithreading, thread safe

​ 多线程并发访问同一个hash表时安全

Hash Map /

Hash Set

支持操作:O(1) Insert / O(1) Find / O(1) Delete

O(size of key)

实现方法:Hash Function

使命:对于任意的key 得到一个固定且无规律的介于0~capacity-1的整数

一些著名的Hash算法 • MD5• SHA-1 • SHA-2

Magic Number - 31经验值

Collision

Open Hashing vs Closed Hashing

再好的 hash 函数也会存在冲突(Collision)

Closed:

Linear Probing: f(i) = i

Quadratic Probing: f(i) = i * i

Double Hashing: f(i) = i * hash2(elem)

Open :duck:

linked list

当hash不够大时怎么办?

饱和度 = 实际存储元素个数 / 总共开辟的空间大小 size / capacity 一般来说,超过 1/10(经验值) 的时候,说明需要进行 rehash

Rehashing: lintcode

• 应用

Longest Word in Dictionary(Trie, prefix tree)

⭐️LRU Cache

\128. Longest Consecutive Sequence

\242. Valid Anagram

\290. Word Pattern

\966. Vowel Spellchecker

49 Group Anagrams

tuple as value of dictionary

Heap

原理

完全二叉树

add(element): logN-->sift up

pop() :logN -->sift down

Get min( ): 1

delete/remove(element): N //need identical-->sift up or down

​ How to get to O(logN): heap + hash map

Minheap: parent <= kids

实现:dynamic array动态数组

array[0]: numbers

i's parent == i//2

i's kids == 2i, 2i+1

if full, expend length

  • 应用:优先队列 Priority Queue

  • 替代品:TreeMap

支持操作:O(log N) Add / O(log N) Remove / O(1) Min or Max Max Heap vs Min Heap

Given an integer array, heapify it into a min-heap array.

For a heap array A, A[0] is the root of heap, and for each A[i], A[i 2 + 1] is the left child of A[i] and A[i 2 + 2] is the right child of A[i].

递归版本,siftup and siftdown

Kth Smallest Element in a Sorted Matrix

\264. Ugly Number II

\263. Ugly Number

\1201. Ugly Number III

\313. Super Ugly Number

545. Top k Largest Numbers II

link code:

mplement a data structure, provide two interfaces:

  1. add(number). Add a new number in the data structure.

  2. topk(). Return the top k largest numbers in this data structure. k is given when we create the data structure.

🌟\23. Merge k Sorted Lists

三种不同的解法:都要掌握

mergeHelper_v1_minHeap 小顶堆(优先队列) mergeHelper_v2_Divide_Conquer 分治思想,递归 mergeHelper_v3_Non_Recursive 两两合并,非递归

时间复杂度均为O(nlogk)

similar problems:

486. Merge K Sorted Arrays

lincode:

Given k sorted integer arrays, merge them into one sorted array.

Example

577. Merge K Sorted Interval Lists

🌟Three solutions to this K-th problem.

973. K Closest Points to Origin

new:

Trapping Rain Water

Trapping Rain Water II

Find Median from Data Stream

Sliding Window Median

Last updated