一、题目
二、代码
class Solution
{
public:
vector<int> topKFrequent(vector<int>& nums, int k)
{
int i,j;
int nums_size;
vector<int> return_vector;
map<int,int> map_for_count;
map<int, int>::iterator pos;
int temp_num;
int max_frequency=0;
nums_size=nums.size();
for(i=0;i<nums_size;i++) //建立字典map
{
// cout<<" here "<<endl;
temp_num=nums[i];
pos=map_for_count.find(temp_num);
if(pos!=map_for_count.end()) //如果找到了
{
pos->second++;
// cout<<" here "<<endl;
}
else //如果没有找到 新建map
{
map_for_count.insert(pair<int,int>(temp_num,1));
// cout<<" here "<<endl;
}
}
for(i=0;i<k;i++)
{
max_frequency=0;
for(map<int,int>::iterator it=map_for_count.begin();it!=map_for_count.end();it++)
{
// cout<<"key= "<<it->first<<"value= "<<it->second<<endl;
if(it->second>max_frequency) //找到大的替换
{
max_frequency=it->second;//更新最大值
pos=it; //更新地址 地址在外部就无法erase 很难说为什么
// std::cout<<"pos->first "<<pos->first<<"pos->second "<<pos->second;
}
}
return_vector.push_back(pos->first);
//std::cout<<"pos->first "<<pos->first<<"pos->second "<<pos->second;
map_for_count.erase(pos);
}
return return_vector;
}
};