Data Structure is a way to organize data. It provides some methods to handle data stream, e.g. insert, delete, etc.
Linear Data Structure
Queue & Stack
Min Stack
Use two stacks, one is storing the input, when calling pop()
or peek()
, pop from another stack, which stores the minimum values from top to bottom.
1 | class MinStack { |
Implement Queue by stacks
Use two stacks, one is for storing elements. When calling pop()
or top()
, pop the elements from the first stack and push them into the second one.
1 | public class Solution { |
Largest Rectangle in Histogram
Brute force: totally O(n^2)
windows and O(n)
to find the minimun one in each window, so we need O(n^3)
time.
Improve: for each number, search both side of it until find two smaller number, calculate the result, O(n^2)
cost.
Best: use a stack to store the index (all increased heights), when faced with a smaller one, pop out from tha stack and calculate the area until the value bigger than the peek() one. This method cost O(n)
time, with O(n)
space in worst case (two passes).
1 | public class Solution { |
expanded: Maximal Rectangle
Max Tree
Method 1: Divide & Conquer - O(n^2)
Method 2: Use stack to build the tree from bottom to top - O(n)
1 | /** |
Hash
How to get Hash Value?
- Easily use MD5 to convert string into integers, and then mod by the size of the hash table.
- Use magic number 33(APR):
1
2
3
4
5
6
7
8int hashFunction(String key) {
int sum = 0;
for(int i = 0; i < key.length(); i++) {
sum = sum * 33 + (int)(key.charAt(i));
sum = sum % Hash_Table_Size;
}
return sum;
}
How to deal with collision?
- Open hashing: use linkedlist(cost extra space)
- Closed hashing: use existed data(cost extra time, worst case O(n))
To get the best performance of Hash Table, we usually insert elements no more than 10% of the hash table’s capacity. When the elements beyond 10%, we will do rehash to expand the capacity(double).
Hash in Java!
Hashtable: thread safe
HashSet and HashMap: not thread safe
Related Problems:
LRU cache
[Longest Consecutive Subsequence]
Tree Data Structure
Heap
In Java, it is PriorityQueue. Basically, a heap is a binary tree. If it is a minimum heap, a node has a smaller value comparing to its children.
Median Number II
Building Outline(Swiping Line Algorithm):
Separate (x1, x2, height) to (x1, height, BUILDING_START), (x2, height, BUILDING_END). Sort all items by x’s ascending order. Swipe the items from left to right, keep a max heap store heights, when meet a BUILDING_START item, insert the height into the heap, when meet a BUILDING_END item, delete the height in the heap. The max height in the heap is height in outline with current x you meet.
Trie
From Retrieve. A kind of dictionary tree, which has 26 children for each node. Here is an implementation of trie tree. A typical problem solving by trie tree is Word Search II, which can be solved by BFS or trie.
Comments