Top K Frequent Elements-347

347. Top K Frequent Elements

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
	struct node {
		int x, y;
		node(int a, int b) {
			x = a; y = b;
		}
		bool operator<(const node&b)const {
			if (y == b.y)  return  x < b.x;
			return y > b.y;
		}
		bool operator>(const node&b)const {
			if (y == b.y)  return  x > b.x;
			return y < b.y;
		}
	};
	vector<int> topKFrequent(vector<int>& nums, int k) {
		unordered_map<int, int>mp;
		for (int i = 0; i < nums.size(); i++) {
			mp[nums[i]]++;
		}
		vector<node>q;
		for (auto &it : mp) {
			q.push_back(node(it.first, it.second));
		}
		sort(q.begin(),q.end());
		vector<int>ans;
		vector<node>::iterator iter = q.begin();
		for (int i = 0 ; i < k; i++) {
			ans.push_back((*iter++).x);
		}
		return ans;
	}
};

int main() {
	vector<int> nums{ 4,1,-1,2,-1,2,3};
	vector<int> res;

	Solution s1;

	res = s1.topKFrequent(nums, 3);
	vector<int>::iterator iter = res.begin();
	for (; iter != res.end(); iter++) {
		cout << *iter;
	}
	system("pause");
	return 0;
}
  • 通过unordered_map存储元素及其对应频数
  • 重载运算符,对unordered_map转化的vector进行排序,注意要考虑y==b.y的情况
  • for (auto &it : mp) 为C++11新特性
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值