HastTable and Dictionary
Overview
There are several similar data structure.
- HashTable / Dictionary
- Key/value
dic = {}
in Pythondic[key] = value
- HashSet
- No repeated values
se = set()
in Pythonse.add(item)
se.remove(item)
The time complexity of search in HashTable’s key or HashSet is O(1)
Useful functions
collections.Counter(list)
can count the element in the list and generate a dictionaryfor key, value in dic.items()
can iterate the key and value at the same timesorted(dic.keys())
is sorting the keysdic.get(key, value)
return the dic[key] if the key in dic, otherwise return value you give
Samples
Used for quick search
No.1 Two Sum
1 | dic = {} |
No.138 Copy List with Random Pointer
No.202 Happy Number
No.136 Single Number
1 | se = set() |
No.217 Contains Duplicate
Used for record the index
No.3 Longest Substring Without Repearting Characters
Used for record the count
No.49 Group Anagrams
1 | dic = {} |
No.347 Top K Frequent Elements
Swap the key and values
1 | form = dict(collections.Counter(nums)) |
No.387 First Unique Character in a String
No.242 Valid Anagram
No.350 Intersection of Two Arrays II
No.36 Valid Sudoku
No.454 4Sum II