哈希:CN97_出现次数的TOPK问题

题目描述:

给定String类型的数组strArr,再给定整数k,请严格按照排名顺序打印 出次数前k名的字符串。

[要求]

如果strArr长度为N,时间复杂度请达到O(N \log K)O(NlogK)

输出K行,每行有一个字符串和一个整数(字符串表示)。
你需要按照出现出现次数由大到小输出,若出现次数相同时字符串字典序较小的优先输出

知识点:

c++优先队列(priority_queue)用法详解

c++ map与unordered_map区别及使用

代码:

#include "stdafx.h"
#include <pair>
#include <queue>
#include <string>
#include<unordered_map>
using namespace std;
class Compare
{
public:
	bool operator()(const pair<int, string>& a, const pair<int, string>& b) const
	{
		if (a.first == b.first) return a.second<b.second;
		return a.first > b.first;
	}
};

class Solution {
public:
	/**
	* return topK string
	* @param strings string字符串vector strings
	* @param k int整型 the k
	* @return string字符串vector<vector<>>
	*/
	vector<vector<string> > topKstrings(vector<string>& strings, int k) {
		//if(strings.empty() || k<=0) return {};

		unordered_map<string, int> mp;
		for (auto str : strings) ++mp[str];

		priority_queue< pair<int, string>, vector<pair<int, string>>, Compare > q;

		auto it = mp.begin();
		for (int i = 0; i<k&&it != mp.end(); ++i)
		{
			q.emplace(it->second, it->first);
			++it;
		}

		while (it != mp.end())
		{
			if (it->second > q.top().first || (it->second == q.top().first && it->first<q.top().second))
			{
				q.pop();
				q.emplace(it->second, it->first);
			}

			++it;
		}

		vector<vector<string>> ret;
		while (!q.empty())
		{
			ret.push_back({ q.top().second, to_string(q.top().first) });
			q.pop();
		}
		reverse(ret.begin(), ret.end());

		return ret;
	}
};

猜你喜欢

转载自blog.csdn.net/haimianjie2012/article/details/109387345