146. LRU Cache
Leetcode: https://leetcode.com/problems/lru-cache/description/
Video: https://www.youtube.com/watch?v=q1Njd3NWvlY&t=28s
[Solution]
- Use two layers of datastructure
- First layer: Dict (HashTable), store key-value pairs
- Second layer: Doubly Linked List, to realize remove tail and insert head in O(1) time
1 | # Define node |
284. Peeking Iterator
Leetcode: https://leetcode.com/problems/peeking-iterator/description/
1 | class PeekingIterator: |
173. Binary Search Tree Iterator
Leetcode: https://leetcode.com/problems/binary-search-tree-iterator/description/
[Solution] Use a stack to store left child of binary tree.
1 | class BSTIterator: |
Generator solution (not quite understand)
1 | def __init__(self, root): |
Note:
- Remember to deal with
root = None
- Use
self.last == self.current
to detect if we reach to the end of the tree
1 | class BSTIterator(object): |
642. Design Search Autocomplete System
155. Min Stack
Leetcode: https://leetcode.com/problems/min-stack/
Note:
- The tricky part is to get the
min
afterpop
operation, if the popped element wasmin
, then we should updatemin
with the second minimum number. - So when we pushing elements into the stack, if
x
is smaller than the currentmin
, we append the currentmin
to the stack as a snapshot of the previous minimum number
1 | class MinStack: |
706. Design HashMap
Leetcode: https://leetcode.com/problems/design-hashmap/
My solution: since the problem limits the input length < 100000, I just set an initial array with length = 100000.
Chain solution: (https://leetcode.com/problems/design-hashmap/discuss/185347/Hash-with-Chaining-Python)
- Use an array of length 1000 with a linkedlist in each cell
1 | class Node: |
348. Design Tic-Tac-Toe
Leetcode: https://leetcode.com/problems/design-tic-tac-toe/
My solution (pretty slow): use a map to keep track of the count of each player on every columns, rows, and diagnoses.
1 | var TicTacToe = function(n) { |
O(1) Solution: when is player 1 we + 1, else we - 1, and see if any of the rows, cols, or diagnoses reach to n
or -n
.
1 | var TicTacToe = function(n) { |
362. Design Hit Counter
Leetcode: https://leetcode.com/problems/design-hit-counter/
Solution:
- Use 2 buckets with length 300, use
times
bucket to record the closest timestamp on the index, usehits
bucket to record the hit numbers
1 | class HitCounter: |