当前位置:网站首页>[Jianzhi offer] 6-10 questions
[Jianzhi offer] 6-10 questions
2022-07-04 22:59:00 【Which bug are you?】
List of articles
Print linked list from end to end
The finger of the sword Offer 06. Print linked list from end to end - Power button (LeetCode)
From the end to the end , You can change the point to , But it's more troublesome , And also changed the structure of the linked list .
Observe the structure of the print , Print the tail first and then print the head , It is very similar to the structure of stack , So use stack to write .
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> st;
vector<int>ret;
ListNode* cur=head;
while(cur!=NULL)
{
st.push(cur->val);
cur=cur->next;
}
int sz=st.size();
ret.resize(sz);
for(int i=0;i<sz;i++)
{
ret[i]=st.top();
st.pop();
}
return ret;
}
};
Reconstruction of binary tree
The finger of the sword Offer 07. Reconstruction of binary tree - Power button (LeetCode)
The idea of building a tree : The first node of the preamble sequence must be the root node , All nodes on the left of the root node in the middle order sequence are left subtrees , The ones on the right are all right subtrees , The specific measures will not be repeated . The following is an analysis from the perspective of code implementation
The difficulty of this problem is to determine the benchmark and the parameters of the recursive function , In fact, the interval is easy to calculate .
Determining the benchmark means whether the subscript position of the elements I use is based on the middle order sequence or the previous order sequence .
Next, I use the position of the root node as the benchmark of the preorder sequence , So in the parameters of recursive function pre_root It represents the position of the root node of the current tree in the previous sequence ,in_root and in_right It represents the left and right boundaries of this tree in the middle order sequence .
class Solution {
public:
//TreeNode* _bulidTree(TreeNode* root,int left,int right)//root If not int You cannot determine the position of the root node in the preorder traversal sequence
TreeNode* _bulidTree(int pre_root,int in_left,int in_right)
{
if(in_left>in_right)// It shows that the left and right subtrees corresponding to this node are unreasonable
{
return NULL;
}
TreeNode* root=new TreeNode(preorder[pre_root]);// Create a root node
int x=find(inorder.begin(),inorder.end(),preorder[pre_root])-inorder.begin();// Find the position of the root node in the middle order sequence
int l_length=x-in_left;// The length of the left section
int r_length=in_right-x;// The length of the right section
root->left=_bulidTree(pre_root+1,in_left,in_left+l_length-1);// Build the left subtree
root->right=_bulidTree(pre_root+l_length+1,in_right-r_length+1,in_right);// Build the right subtree
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
this->preorder=preorder;// Let the subfunction _buildTree You can get preorder
this->inorder=inorder;// Empathy
TreeNode* root=_bulidTree(0,0,preorder.size()-1);// Both sides of my interval are closed
return root;
}
private:
vector<int> preorder;
vector<int> inorder;
};
This code also has an optimization point , Careful observation shows that every recursion I have to calculate the position of the root node in the middle order sequence , and find The bottom of the is to find one by one , The efficiency is not high , So here we can use the idea of hash to map the position of the root node in the middle order sequence .
class Solution {
public:
//TreeNode* _bulidTree(TreeNode* root,int left,int right)//root If it is not for shaping, the position of the root node in the preorder traversal sequence cannot be determined
TreeNode* _bulidTree(int pre_root,int in_left,int in_right)
{
if(in_left>in_right)
{
return NULL;
}
TreeNode* root=new TreeNode(preorder[pre_root]);
// int x=find(inorder.begin(),inorder.end(),preorder[pre_root])-inorder.begin();
int l_length=dic[preorder[pre_root]]-in_left;// The length of the left section
int r_length=in_right-dic[preorder[pre_root]];// The length of the right section
root->left=_bulidTree(pre_root+1,in_left,in_left+l_length-1);
root->right=_bulidTree(pre_root+l_length+1,in_right-r_length+1,in_right);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
this->preorder=preorder;
for(int i=0;i<inorder.size();i++)
{
dic[inorder[i]]=i;// Subscripts of ordered sequence elements in mapping
}
TreeNode* root=_bulidTree(0,0,preorder.size()-1);
return root;
}
private:
vector<int> preorder;
vector<int> inorder;
unordered_map<int,int>dic;// Dictionaries , Represents a mapping relationship
};
The next node of a binary tree
There is no link found in this question
Find the next node of the middle order traversal
I used to write about red and black trees ++ I wrote something similar , Here, paste the code at that time , The details are as follows (
This picture is the content of my red black tree blog)
self& operator++()// In front of ++
{
Node* cur = _node;
if (cur->_right)
{
// The right subtree is not empty , You can't directly give the root of the right subtree to _node
// Because the leftmost leaf of the right subtree is the next node that should be accessed
Node* right = cur->_right;
while (right&&right->_left)
{
right = right->_left;
}
_node = right;
return *this;
}
else// The right subtree is empty
// Look at my father
{
Node* parent = cur->_parent;
while (parent&&parent->_right == cur)
{
cur = parent;
parent = cur->_parent;
}
if (parent == nullptr)
{
_node = nullptr;
}
else
{
_node = parent;
}
return *this;
}
}
Queues are implemented with two stacks
The finger of the sword Offer 09. Queues are implemented with two stacks - Power button (LeetCode)
Use two stacks to simulate the implementation of queues .
Pay special attention to the empty stack , If you don't handle the empty stack, you can't compile it (VS Run too fast )
class CQueue {
public:
CQueue() {}
void appendTail(int value) {
st1.push(value);
}
int deleteHead() {
if(st1.empty()&&st2.empty())// Consider the case that both stacks are empty , because _ move Empty stack is not handled
// If both incoming stacks are empty , It can lead to stack An error is reported when accessing the data at the top of the stack when it is empty
{
return -1;
}
_move(st1,st2);
int x=st2.top();
st2.pop();
_move(st2,st1);
return x;
}
void _move(stack<int>&s1,stack<int>&s2)// hold s1 Move your data to s2 Inside
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
private:
stack<int>st1;
stack<int>st2;
};
Fibonacci sequence
The finger of the sword Offer 10- I. Fibonacci sequence - Power button (LeetCode)
According to the formula given by the topic, you can recurse .
class Solution {
public:
int fib(int n) {
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
int pprev=0;// Previous to current number
int prev=1;// The previous of the current number
for(int i=2;i<=n;i++)
{
int tmp=(prev+pprev)%1000000007;
pprev=prev%1000000007;
prev=tmp;
}
return prev;// The result of the last calculation is tmp Give it to prev
}
}
};
There is also a kind of logn Solution method , But it's complicated to write , Not enough practical .
【 Expand 】 Frogs jump the steps
Fibonacci's deformation , It can also be used. dp To do .
Remember the frog jumping on the first n The number of schemes for the ladder is dp[n]; be dp[n]=dp[n-1]+dp[n-2]; For example, the frog is in the first N Steps , Then it can only be from N-1 Or N-2 Up the grade
class Solution {
public:
int numWays(int n) {
int a[]={
1,1};
if(n<2)
{
return a[n];
}
int ans=0;
int pprev=1;
int prev=1;
for(int i=2;i<=n;i++)
{
ans=(pprev+prev)%1000000007;
pprev=prev%1000000007;
prev=ans;
}
return ans;
}
};
【 Expand 】 Rectangular overlay
No link found for this question … But it is also Fibonacci's deformation .

边栏推荐
- On-off and on-off of quality system construction
- leetcode 72. Edit distance edit distance (medium)
- P2181 对角线和P1030 [NOIP2001 普及组] 求先序排列
- Unity修仙手游 | lua动态滑动功能(3种源码具体实现)
- Redis: redis configuration file related configuration and redis persistence
- 攻防世界 misc 高手进阶区 a_good_idea
- Insert sort, select sort, bubble sort
- [odx Studio Edit pdx] - 0.2 - Comment comparer deux fichiers pdx / odx
- 攻防世界 MISC 进阶区 hit-the-core
- Record: how to scroll screenshots of web pages on Microsoft edge in win10 system?
猜你喜欢

Advanced area of attack and defense world misc 3-11

Wake up day, how do I step by step towards the road of software testing

Redis入门完整教程:HyperLogLog
![[machine learning] handwritten digit recognition](/img/26/cabdc5c92035181d82f6f809e6df0f.png)
[machine learning] handwritten digit recognition

攻防世界 misc 进阶区 2017_Dating_in_Singapore

NFT insider 64: e-commerce giant eBay submitted an NFT related trademark application, and KPMG will invest $30million in Web3 and metauniverse

Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf

sobel过滤器

10 schemes to ensure interface data security
![P2181 diagonal and p1030 [noip2001 popularization group] arrange in order](/img/79/36c46421bce08284838f68f11cda29.png)
P2181 diagonal and p1030 [noip2001 popularization group] arrange in order
随机推荐
Complete tutorial for getting started with redis: bitmaps
Li Kou 98: verify binary search tree
Is Huatai Securities a nationally recognized securities firm? Is it safe to open an account?
Redis入门完整教程:HyperLogLog
SQL中MAX与GREATEST的区别
[Lua] Int64 support
Lost in the lock world of MySQL
Gnawing down the big bone - sorting (II)
该如何去选择证券公司,手机上开户安不安全
Redis入门完整教程:集合详解
Erik baleog and Olaf, advanced area of misc in the attack and defense world
Taobao commodity review API interface (item_review get Taobao commodity review API interface), tmall commodity review API interface
10 schemes to ensure interface data security
Common methods in string class
微信小程序显示样式知识点总结
页面关闭前,如何发送一个可靠请求
Redis getting started complete tutorial: publish and subscribe
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
攻防世界 MISC 进阶区 Ditf
Detailed explanation of heap sort code
