Learn from leetCode
Some strategy learning from leetCode
C++ 2d array
Better use a vector(don’t need to consider allocator)
|
|
|
|
Traverse a tree
The tree structure:
|
|
BFS DFS Pre-order In-order Post-order for a tree
Loop for BFS:
|
|
Loop for DFS:
|
|
Pre-order: (DFS is same)
|
|
In-Order:
|
|
Pre-Order: (Bottom-to-up)
|
|
BFS process level by level
|
|
heap
Function make_heap
can be used to arrange vector into a heap.
It is better to use adopter priority_queue
as heap.
|
|
Faster io for C++
At this part at beginning.
Relative article: Fast I/O for Competitive Programming - GeeksforGeeks
|
|
Binary search tree(BST) & In-order traversal
After In-order traverse a BST, the result is a sorted sequence.
Also you can use a sorted sequence to rebuild a balance BST.
LeetCode 109 Convert Sorted List to Binary Search Tree
DFS & Backtracking
Example for DFS: LeetCode200
Example for Backtracking: LeetCode46
The different between them is: Backtracking will set the current state back after recursion.
Since they all traverse a matrix, they both need to worry about recursive back. Like DFS goes from left to right and how to protect go back from right left. Of course, sometime it don’t need to be considered.
Word ladder problem
Give a begin word, an end word and a word dictionary.
Word Ladder: leetCode 127
The idea to solve this question is to build a graph (or a State machine) and BFS the graph.
Minimum Genetic Mutation: leetCode 433
Tis question don’t have to build a graph since each char only have 4 options. We can just check the one word mutation is stay in dictionary or not.
Sum O(n^2) -> O(n)
If you want to find all continuous sum in a vector, the naive method is using two for loop:
|
|
We can use some tech to make time complexity down to O(n)
The key idea is sum(i, j) = sum(0, j) - sum(0, i-1)
;
Monotonic Queue
A monotonic queue is a data structure that all elements is strictly increasing or decreasing.
Any new element only entry at the end of the queue and tick out the elements in the queue to make sure the queue is still monotonic.
Example
[5,3,1,2,4]
index | v | Increasing queue | Decreasing queue |
---|---|---|---|
1 | 5 | [5] | [5] |
2 | 3 | [3] | [5,3] |
3 | 1 | [1] | [5,3,1] |
4 | 2 | [1,2] | [5,3,2] |
5 | 4 | [1,2,4] | [5,4] |
Questions
leetcode 581: Shortest Unsorted Continuous Subarray
Convert a number to a binary string (and back) in C++
Use bitset to easily achieve that.
See my previous post
Question
leetCode 190:Reverse Bits