使用优先队列解决自己构造的数据类型

在C++中优先队列有两种,最大堆和最小堆。当数据类型为int的时候,大家都会使用,但是如果数据不是单一的,比如数据是一个hashmap怎么办?例子如下:

You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.

For each index inames[i] and heights[i] denote the name and height of the ith person.

Return names sorted in descending order by the people's heights.

Example 1:

Input: names = ["Mary","John","Emma"], heights = [180,165,170]
Output: ["Mary","Emma","John"]
Explanation: Mary is the tallest, followed by Emma and John.

Example 2:

Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]
Explanation: The first Bob is the tallest, followed by Alice and the second Bob.

使用优先队列,将会十分简单,难点在于怎么包含两种类型,于是想到了pair这个神奇的东西。然后就是最大堆的比较函数,需要写一个结构体,声明比较函数。于是代码如下:

class Solution {
    typedef pair<string,int> PSI;
    struct cmp
    {
        bool operator()(PSI a, PSI b)
        {
            return a.second<b.second;
        }
    };
public:
    vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
        priority_queue<PSI,vector<PSI>,cmp> pq;
        vector<string> ans;
        for(int i=0;i<heights.size();i++)
        {
            pq.push({names[i],heights[i]});
        }
        while(!pq.empty())
        {
            ans.push_back(pq.top().first);
            pq.pop();
        }
        return ans;
    }
};

 当然,这只是一个解题的模板,因为题目中说身高互不相同,这种方法并没有考虑这个特性,并不是最优解。其他贪心的算法,也可以构建这样的结构来求解。

猜你喜欢

转载自blog.csdn.net/weixin_41579872/article/details/130367523