中级农民
- 积分
- 115
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-12-7
- 最后登录
- 1970-1-1
|
7月打卡第四天
刷题六道
1.Print Layer by Layer
-用好Queue
-最简单的BFS
2.Zig-zag print
-用好Deque,双端队列
-按照题目意思来进行根据层数奇偶行来的划分
-决定在这一层poll和offer的顺序
-无论如何poll和offer不再同一边
3.Check if it is complete tree
-use a flag to detect if it is true already
-if true and meet other element under just return false
-until traversing all elements then return true;
4.Bipartite(如何去确定它的颜色?在HashMap里面设置)
-关键是用好Map这个数据结构
-<K,V>里面的V是Integer,标记一下颜色就好
5.TopKinUnsortedArray
-两种方法:minHeap / maxHeap
-1.minHeap N + klogN;
-2.maxHeap k + klogk
6.KthSmallestSortedMatrix
High level:
this is BFS2 question which the value of each upcoming element is not identical
so a general queue is not enough, so a priorityQueue(A.K.K minHeap) can be used to solve this problem.
Details:
Firstly, do the corner case check, the matrix can't be null or empty,
also, k must be valid(k >= 1 && k <= matrix.length * matrix[0].length)
Use a MinHeap with a hashMap which contains traversed coordinate positions so to avoid deduplication
Set up a new class Cell so the row, the col and the value of each element can be recorded in it;
Secondly,
Initialization: use the original point parameters(row, col, val) to create a new Cell;
and put it into the minHeap, also, checked new Cell has been visited;
Thirdly,
Then in the while loop,
which the terminal condition is k <= 1
during each single process, get the current element and check if the two neighbors of current one can be
added into the minHeap or not;
update the minHeap and the visited hashMap;
update k(k--);
Finally,
After jump out the loop, we already poll out K - 1 element, so just return the top one at the min Heap and return it;
|
|