当前位置:网站首页>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 :
边栏推荐
- Semantic SLAM源码解析
- Training IX basic configuration of network services
- 爬虫实战(七):爬王者英雄图片
- Empowering smart power construction | Kirin Xin'an high availability cluster management system to ensure the continuity of users' key businesses
- 模拟实现string类
- Time tools
- The research group of the Hunan Organizing Committee of the 24th China Association for science and technology visited Kirin Xin'an
- R语言ggplot2可视化:使用ggpubr包的ggdensity函数可视化分组密度图、使用stat_overlay_normal_density函数为每个分组的密度图叠加正太分布曲线
- 最多可以参加的会议数目[贪心 + 优先队列]
- 小试牛刀之NunJucks模板引擎
猜你喜欢
Automatic classification of defective photovoltaic module cells in electroluminescence images-论文阅读笔记
The project manager's "eight interview questions" is equal to a meeting
论文解读(ValidUtil)《Rethinking the Setting of Semi-supervised Learning on Graphs》
8 CAS
Dynamic addition of El upload upload component; El upload dynamically uploads files; El upload distinguishes which component uploads the file.
开源重器!九章云极DataCanvas公司YLearn因果学习开源项目即将发布!
Kunpeng developer summit 2022 | Kirin Xin'an and Kunpeng jointly build a new ecosystem of computing industry
openEuler 有奖捉虫活动,来参与一下?
Navicat连接2002 - Can‘t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock‘解决
索引总结(突击版本)
随机推荐
Semantic SLAM源码解析
Ucloud is a basic cloud computing service provider
使用高斯Redis实现二级索引
# 欢迎使用Markdown编辑器
LeetCode 515(C#)
LC:字符串转换整数 (atoi) + 外观数列 + 最长公共前缀
Download from MySQL official website: mysql8 for Linux X Version (Graphic explanation)
R语言fpc包的dbscan函数对数据进行密度聚类分析、查看所有样本的聚类标签、table函数计算聚类簇标签与实际标签构成的二维列联表
现在股票开户可以直接在网上开吗?安全吗。
LeetCode_7_5
UCloud是基础云计算服务提供商
Classification automatique des cellules de modules photovoltaïques par défaut dans les images de lecture électronique - notes de lecture de thèse
Navicat连接2002 - Can‘t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock‘解决
Redis——基本使用(key、String、List、Set 、Zset 、Hash、Geo、Bitmap、Hyperloglog、事务 )
网信办公布《数据出境安全评估办法》,9 月 1 日起施行
R语言ggplot2可视化:使用ggpubr包的ggdensity函数可视化分组密度图、使用stat_overlay_normal_density函数为每个分组的密度图叠加正太分布曲线
Visual Studio 插件之CodeMaid自动整理代码
我的创作纪念日
9 原子操作类之18罗汉增强
Matplotlib drawing 3D graphics