Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(!t1&&!t2)
return nullptr;
TreeNode *node=new TreeNode((t1?t1->val:0)+(t2?t2->val:0));
node->left=mergeTrees((t1?t1->left:nullptr),(t2?t2->left:nullptr));
node->right=mergeTrees((t1?t1->right:nullptr),(t2?t2->right:nullptr));
return node;
}
};
在对左右子树进行拓展时,要注意当前两棵树的节点是否为空。
问题: Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard
class Solution {
public:
vector<string> findWords(vector<string>& words) {
unordered_set<char> s1={'q','w','e','r','t','y','u','i','o','p'};
unordered_set<char> s2={'a','s','d','f','g','h','j','k','l'};
unordered_set<char> s3={'z','x','c','v','b','n','m'};
vector<unordered_set<char>> vec {s1,s2,s3};
vector<string> str;
for(int i=0;i<words.size();i++){
int m1=0;
for(int j=0;j<3;j++){
if(vec[j].count(tolower(words[i][0]))>0)
m1=j;
}
str.push_back(words[i]);
for(int k=1;k<words[i].size();k++){
if(vec[m1].count(tolower(words[i][k]))==0)
{
str.pop_back();
break;
}
}
}
return str;
}
};
思路:在这里使用了set中的count成员函数。用来计算字符在set中出现的次数。将每一行的字符都存储在一个unordered_set中,然后三个set初始化一个vector。先找到每个单词第一个字符在哪个set集合中出现,如果该单词的所有字符都出自同一个set,则对每一个单词的字符都计算其count值,这样就能判断是否由同一行的字符组成的单词
问题:
Top K Frequent Elements
思路:算法要求时间复杂度至少是O(n log n),使用了最大堆数据结构。
这里涉及到了优先队列,具体的内容详见参考链接
http://blog.csdn.net/senyelicone/article/details/51850284
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> mymap;
for(int i=0;i<nums.size();i++){
mymap[nums[i]]++;
}
vector<int> ret;
priority_queue<pair<int,int>>pq;
for(auto it=mymap.begin();it!=mymap.end();it++){
pq.push(make_pair(it->second,it->first));
if(pq.size()>mymap.size()-k){
ret.push_back(pq.top().second);
pq.pop();
}
}
return ret;
}
};