当前位置:网站首页>Sword finger offer2: queue summary
Sword finger offer2: queue summary
2022-06-13 02:45:00 【Zeng Qiang】
List of articles
The basics of queues : fifo
queue Queue Is an internal element characteristic that conforms to ” fifo “ Data set for . If data deletion and insertion operations are met when solving the problem " fifo " Characteristics , Then consider using queues to store this data .
- frequently-used API
operation | No abnormal protection | With abnormal protection |
---|---|---|
Add an element to the end of the team | add(node) | offer(node ) |
Remove an element from the team leader | remove(node) | poll(node) |
Returns the first element | element() | peek() |
Java The commonly used queue implementation classes in LinkedList, ArrayDeque, PriorityQueue. however PriorityQueue Not a queue data structure , It's a pile .
application
The sliding window
The finger of the sword Offer II 041. Average value of sliding window
Please implement the following types MovingAverage, Calculate the average of all numbers in the sliding window , The parameters of this type constructor determine the size of the sliding window , Every time a member function is called next An integer will be added to the sliding window , And returns the average of all the numbers in the sliding window .
Their thinking
This topic is mainly divided into two parts :
- Maintain sliding windows :
After adding the elements of the window , If the number of window elements is greater than the limit , You need to delete the element you first added .
This is consistent with the first in, first out feature . So we can think about it queue To maintain the sliding window as a data set . - Calculate average :
Calculate the sum of window elements , Just add the value of one element at a time , Then subtract the value of the deleted element , The time complexity is O(1).
The specific code is as follows :
Code
class MovingAverage {
private Queue<Integer> queue;
private int capacity = 0;
private int sum = 0;
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.capacity = size;
queue = new LinkedList<>();
}
public double next(int val) {
queue.offer(val);
sum += val;
if(queue.size() > this.capacity) {
sum -= queue.poll();
}
return (double)sum / queue.size();
}
}
The finger of the sword Offer II 042. Number of recent requests
subject : Please implement the following types RecentCounter, It counts the past 3000ms A counter for the number of requests within . Constructor of this type RecentCounter Initialize counter , The number of requests is initialized to 0; function ping(int t) In time t Add a new request (t Represents the time in milliseconds ), And go back to the past 3000ms Inside ( The time frame is [t-3000,t]) Number of all requests that occurred . Suppose every time you call a function ping Parameters of t Is larger than the parameter value of the previous call .
Their thinking
1. Select the data structure : Subject requirements 3000 Milliseconds to the current time t Number of requests in , Then we need to use a data container to store the time points of historical requests , At the same time, delete the interval 【3000-t,t] Time point outside .
2. The sliding window : Because of the logic of Statistics , In line with the characteristics of first in first out , So queues can be used as data sets , Maintain a sliding window , Every time ping New requests , Move the window forward .
The specific code is as follows :
Code
class RecentCounter {
private Queue<Integer> times;
private int windowSize;
public RecentCounter() {
windowSize = 3000;
times = new LinkedList<>();
}
public int ping(int t) {
times.offer(t);
while((times.peek() + windowSize) < t) {
times.poll();
}
return times.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
Breadth first search
Problem solving skills : If the interview question of binary tree , Encounter the concept of layer , You can try to use breadth first search to solve such problems .
Breadth first search traversal steps :
- Define the queue , hold root Queue .
- Traverse the current layer . According to the current queue length , Get the number of nodes in the current layer , Start traversing the nodes of the current layer .
- Record the nodes of the next layer , When traversing the current layer node , We can save the left and right nodes at the next level of the node to the queue .
The finger of the sword Offer II 043. Add nodes to a complete binary tree
subject : A complete binary tree is every layer ( Except for the last floor ) All completely filled ( namely , The number of nodes reaches the maximum , The first n Layer has a 2n-1 Nodes ) Of , And all nodes are concentrated on the left as much as possible .
Design a data structure initialized with a complete binary tree CBTInserter, It supports the following operations :
CBTInserter(TreeNode root) Use root node as root Initialize the data structure for the given tree ;
CBTInserter.insert(int v) Insert a new node into the tree , The node type is TreeNode, The value is v . Keep the tree in the state of a complete binary tree , And return the value of the parent node of the inserted new node ;
CBTInserter.get_root() Will return the root node of the tree .
Their thinking
To solve this problem, we should master two knowledge points
- The characteristics of complete binary tree
A binary tree , From top to bottom , Add nodes from left to right . - Breadth first search , Find the parent node where you can add nodes .
Use the queue to traverse the binary tree by layer , When the left or right child nodes of the traversal node are empty , Then the pointer to the node that can be added is found .
The specific implementation is as follows :
Code
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class CBTInserter {
private Queue<TreeNode> queue;
private boolean isLeft;
private TreeNode root;
public CBTInserter(TreeNode root) {
queue = new ArrayDeque<>();
this.root = root;
queue.offer(root);
//1. Initialize queue , Find the parent node where the child node can be inserted .
while(!queue.isEmpty()) {
TreeNode node = queue.peek();
if(node.left == null) {
isLeft = true;
break;
} else {
queue.offer(node.left);
}
if(node.right == null) {
isLeft = false;
break;
} else {
queue.offer(node.right);
queue.poll();// It's full on both sides , Then this node cannot insert child nodes , So remove it from the queue .
}
}
}
public int insert(int v) {
//queue The queue head node of is the parent node to be inserted
TreeNode parent = queue.peek();
TreeNode newNode = new TreeNode(v);
if(isLeft) {
parent.left = newNode;
} else {
parent.right = newNode;
queue.poll();
isLeft = false;
}
isLeft = !isLeft;
queue.offer(newNode);
return parent.val;
}
public TreeNode get_root() {
return root;
}
}
/** * Your CBTInserter object will be instantiated and called as such: * CBTInserter obj = new CBTInserter(root); * int param_1 = obj.insert(v); * TreeNode param_2 = obj.get_root(); */
The finger of the sword Offer II 044. Maximum value of each layer of binary tree
Given the root node of a binary tree root , Please find the maximum value of each layer in the binary tree .
Their thinking
If there are layers in the binary tree , You can try to use breadth first search to traverse a binary tree , Calculate the maximum value of each layer .
In two steps :
- Define data container queues , Traversing the binary tree .
- Count the maximum value of each layer .
Use for Loop through each layer , At the same time, you can join the next layer of nodes .
The specific code is as follows :
Code
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
public List<Integer> largestValues(TreeNode root) {
if(root == null) {
return new ArrayList<Integer>();
}
// To a binary tree , Sequence traversal
// Find out the maximum value of each layer
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> result = new ArrayList();
queue.offer(root);
while(!queue.isEmpty()) {
int max = Integer.MIN_VALUE;
int size = queue.size();// The number of nodes in each layer
for(int i = 0; i < size; i++) {
TreeNode node = queue.poll();
max = node.val > max ? node.val : max;// Count the maximum value of each layer
if(node.left !=null ) queue.offer(node.left);// Record the nodes of the next layer
if(node.right !=null ) queue.offer(node.right);// Record the nodes of the next layer
}
result.add(max);
}
return result;
}
}
summary
A queue is a first in, first out data structure , It is generally used to deal with sliding window problems and breadth first search problems . When encountering the problem of binary tree layer , Try using breadth first search to traverse .
边栏推荐
- Matlab: find the inner angle of n-sided concave polygon
- Find the number of permutations
- redis. Conf general configuration details
- Detailed explanation of UCI datasets and their data processing (with 148 datasets and processing codes attached)
- Detailed installation tutorial of MATLAB r2019 B-mode ultrasound (complete installation files are attached)
- 智能安全配电装置如何减少电气火灾事故的发生?
- A wechat app for shopping
- [dest0g3 520 orientation] dest0g3, which has been a long time since we got WP_ heap
- Opencv 15 face recognition and eye recognition
- Ijkplayer source code - choose soft decoding or hard decoding
猜你喜欢
[life science] DNA extraction of basic biological experiments
Data warehouse notes | 5 factors that need attention for customer dimension modeling
冲刺强基计划数学物理专题一
How to destroy a fragment- How to destroy Fragment?
AAR packaging and confusion
[reading papers] comparison of deeplobv1-v3 series, brief review
Prometheus安装并注册服务
Detailed explanation of handwritten numeral recognition based on support vector machine (Matlab GUI code, providing handwriting pad)
CDN single page reference of indexbar index column in vant framework cannot be displayed normally
Logiciel professionnel de gestion de base de données: Valentina Studio Pro pour Mac
随机推荐
01 initial knowledge of wechat applet
Opencv 15 face recognition and eye recognition
Bi modal progressive mask attention for fine graded recognition
Prometheus node_ Exporter installs and registers as a service
Model prediction of semantic segmentation
Use of OpenCV 11 kmeans clustering
微信云开发粗糙理解
Rough understanding of wechat cloud development
[thoughts in the essay] mourn for development technology expert Mao Xingyun
Linear, integer, nonlinear, dynamic programming
HEAP[xxx.exe]: Invalid address specified to RtlValidateHeap( 0xxxxxx, 0x000xx)
OneNote使用指南(一)
数仓笔记|针对客户维度建模需要关注的5个因素
[data and Analysis Visualization] D3 introductory tutorial 1-d3 basic knowledge
Prometheus node_exporter安装并注册为服务
[data analysis and visualization] key points of data drawing 5- the problem of error line
Opencv 07, pixel read, change and bitmap write
Prometheus install and register services
Principle and steps of principal component analysis (PCA)
CV 06 demonstrates backgroundworker