当前位置:网站首页>Leetcode force buckle (Sword finger offer 36-39) 36 Binary search tree and bidirectional linked list 37 Serialize binary tree 38 Arrangement of strings 39 Numbers that appear more than half of the tim
Leetcode force buckle (Sword finger offer 36-39) 36 Binary search tree and bidirectional linked list 37 Serialize binary tree 38 Arrangement of strings 39 Numbers that appear more than half of the tim
2022-07-07 19:57:00 【Wood White CPP】
The finger of the sword Offer 36. Binary search tree and double linked list
Answer key :
The idea is simple , It is a medium order traversal , Connect nodes while traversing .
Code :
class Solution {
public:
Node *pre,*head;
void dfs(Node* root){
if(root==nullptr) return;
dfs(root->left);
if(pre==nullptr) head=root;// This is a header node
else
pre->right=root;
root->left=pre;
pre=root;
dfs(root->right);
}
Node* treeToDoublyList(Node* root) {
if(root == nullptr) return root;
dfs(root);
head->left=pre;
pre->right=head;
return head;
}
};
result :
The finger of the sword Offer 37. Serialize binary tree
Answer key :
Serialization generally adopts pre order , Middle preface , In the following order , Here we use the preface .
serialize , Use preorder traversal to save the nodes of the binary tree into a string , Between each node ’,‘ separate . It is worth noting that , In the process of traversal, we need to treat the binary tree as a full binary tree , Blank nodes with ’null‘ Express .
Deserialization , Put the string in the queue que in , use ’,‘ Judge and push into the queue . Traverse through the preamble , While traversing the preorder, establish a binary tree node .
Code :
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(root==nullptr) return "null,";
string str=to_string(root->val)+',' ;
str+=serialize(root->left);
str+=serialize(root->right);
return str;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
queue<string> que;
string str;
for(auto i:data){
if(i==','){
que.push(str);
str.clear();
}
else
str.push_back(i);
}
return rdeserialize(que);
}
TreeNode* rdeserialize(queue<string> &que){
if (que.front() == "null") {
que.pop();
return nullptr;
}
TreeNode* root = new TreeNode(stoi(que.front()));
que.pop();
root->left = rdeserialize(que);
root->right = rdeserialize(que);
return root;
}
};
result :
The finger of the sword Offer 38. Arrangement of strings
Answer key :
The key is to repeat , Because there are repeated characters . You can use a flag bit , Judge whether the current character appears in the previous string .
Code :
class Solution {
public:
vector<string> res;
void dfs(string &s,int sz,int pos){
if(pos==sz) res.push_back(s);
for(int i=pos;i<sz;++i){
bool flag=true;
for(int j=pos;j<i;++j){
if(s[j]==s[i]) flag=false;
}
if(flag){
swap(s[i],s[pos]);
dfs(s,sz,pos+1);
swap(s[i],s[pos]);
}
}
}
vector<string> permutation(string s) {
dfs(s,s.size(),0);
return res;
}
};
result :
The finger of the sword Offer 39. A number that appears more than half the times in an array
There is a number in an array that appears more than half the length of the array , Please find out the number .
You can assume that the array is not empty , And there are always many elements in a given array .
Answer key :
Method 1 : Sort
If there are more than half of the repeated characters , After sorting, it must be in the middle of the array .
Code :
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}
};
result :
Method 2 : Hash
Store with hash , Once the value is greater than half the length of the array, the value is returned .
Code :
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int>map;
for(auto i:nums){
++map[i];
if(map[i]>nums.size()/2) return i;
}
return -1;
}
};
result :
边栏推荐
- 剑指 Offer II 013. 二维子矩阵的和
- Solve the error reporting problem of rosdep
- Jürgen Schmidhuber回顾LSTM论文等发表25周年:Long Short-Term Memory. All computable metaverses. Hierarchical reinforcement learning (RL). Meta-RL. Abstractions in generative adversarial RL. Soccer learn
- Flink并行度和Slot详解
- R language uses ggplot2 function to visualize the histogram distribution of counting target variables that need to build Poisson regression model, and analyzes the feasibility of building Poisson regr
- 干货分享|DevExpress v22.1原版帮助文档下载集合
- Empowering smart power construction | Kirin Xin'an high availability cluster management system to ensure the continuity of users' key businesses
- R语言dplyr包mutate_at函数和min_rank函数计算dataframe中指定数据列的排序序号值、名次值、将最大值的rank值赋值为1
- R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、设置palette参数自定义不同水平小提琴图的填充色、add参数在小提琴图添加箱图
- Training IX basic configuration of network services
猜你喜欢
Kirin Xin'an won the bid for the new generation dispatching project of State Grid!
el-upload上传组件的动态添加;el-upload动态上传文件;el-upload区分文件是哪个组件上传的。
8 CAS
PMP每日一练 | 考试不迷路-7.7
Empowering smart power construction | Kirin Xin'an high availability cluster management system to ensure the continuity of users' key businesses
# 欢迎使用Markdown编辑器
LeetCode力扣(剑指offer 36-39)36. 二叉搜索树与双向链表37. 序列化二叉树38. 字符串的排列39. 数组中出现次数超过一半的数字
Install mysql8 for Linux X ultra detailed graphic tutorial
Responsibility chain model - unity
Automatic classification of defective photovoltaic module cells in electroluminescence images-論文閱讀筆記
随机推荐
Implement secondary index with Gaussian redis
索引总结(突击版本)
Visual Studio 插件之CodeMaid自动整理代码
Kirin Xin'an joins Ningxia commercial cipher Association
openEuler 资源利用率提升之道 01:概论
PMP對工作有益嗎?怎麼選擇靠譜平臺讓備考更省心省力!!!
Browse the purpose of point setting
LeetCode力扣(剑指offer 36-39)36. 二叉搜索树与双向链表37. 序列化二叉树38. 字符串的排列39. 数组中出现次数超过一半的数字
项目经理『面试八问』,看了等于会了
浏览积分设置的目的
Time tools
Install mysql8 for Linux X ultra detailed graphic tutorial
Mysql, sqlserver Oracle database connection mode
Netease Yunxin participated in the preparation of the standard "real time audio and video service (RTC) basic capability requirements and evaluation methods" issued by the Chinese Academy of Communica
Redis——基本使用(key、String、List、Set 、Zset 、Hash、Geo、Bitmap、Hyperloglog、事务 )
【RT-Thread env 工具安装】
微信公众号OAuth2.0授权登录并显示用户信息
时间工具类
Tp6 realize Commission ranking
R language ggplot2 visualization: use the ggqqplot function of ggpubr package to visualize the QQ graph (Quantitative quantitative plot)