给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
- 输入: nums = [1,1,1,2,2,3], k = 2
- 输出: [1,2]
class Solution {
public:
class mycomparison{
public:
bool operator()(const pair<int,int>&lhs,const pair<int,int>&rhs)
{
return lhs.second>rhs.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int>map;
for(int i=0;i<nums.size();i++)
{
map[nums[i]]++;
}
priority_queue<pair<int,int>,vector<pair<int,int>>,mycomparison> pri_que;
for(unordered_map<int,int>::iterator it=map.begin();it!=map.end();it++)
{
pri_que.push(*it);
if(pri_que.size()>k)
{// 如果堆的大小大于了K,则队列弹出,保证堆的大小一直为k
pri_que.pop();
}
}
// 找出前K个高频元素,因为小顶堆先弹出的是最小的
vector<int>result;
while(!pri_que.empty())
{
result.push_back(pri_que.top().first);
pri_que.pop();
}
return result;
}
};
class Solution {
public:
void Traversal(TreeNode*cur,vector<int>&vec)
{
if(cur==nullptr)
return ;
Traversal(cur->left,vec);
vec.push_back(cur->val);
Traversal(cur->right,vec);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int>result;
Traversal(root,result);
return result;
}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int>vec;
if(root==nullptr)return vec;
st.push(root);
while(!st.empty())
{
TreeNode*node=st.top();
st.pop();
vec.push_back(node->val);
if(node->right)st.push(node->right);
if(node->left)st.push(node->left);
}
return vec;
}
};
class Solution {
public:
vector<int>inorderTraversal(TreeNode*root)
{
stack<TreeNode*>st;
vector<int>result;
TreeNode* cur=root;
while(cur!=nullptr||!st.empty())
{
if(cur!=nullptr)
{
st.push(cur);
cur=cur->left;
}
else
{
cur=st.top();
st.pop();
result.push_back(cur->val);
cur=cur->right;
}
}
return result;
}
};