微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过问题了解priority_queue : Find K Closest Elements Solution

如何解决通过问题了解priority_queue : Find K Closest Elements Solution

我正在解决 leetcode problem 上的一个问题 - 找到 K 个最近的元素

这是我的 IDE 代码ide.geeksforgeeks

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

std::vector<int> findClosestElements(std::vector<int>& arr,int k,int x) 
{
    std::vector<int> res;
    // min heap
    std::priority_queue<std::pair<int,int>,std::vector<std::pair<int,int>>,std::greater<std::pair<int,int>>> pq;
    
    std::cout << "Debug queue : \n";
    for (auto it : arr)
    {
        int closest = abs(it - x);
        pq.push(std::make_pair(closest,it));        
        //std::cout << closest << " : " << it << "\n";
        
        if (pq.size() > k)
        {
            pq.pop();     
        }
    }
    
    std::cout << "\nIterating queue : \n";
    while(!pq.empty())
    {
        res.push_back(pq.top().second);
        std::cout << pq.top().first << " : " << pq.top().second << "\n";
        pq.pop();
    }
    
    std::sort(res.begin(),res.end());
    return res;
}

int main()
{
    std::vector<int> arr = {1,2,3,4,5};
    auto res = findClosestElements(arr,3);
    return 0;
}

当我迭代队列时,我看不到最小数量0 : 3,它应该是 priority_queue 的顶部元素。任何人都可以请推荐吗?

解决方法

最大堆解决了这个问题。

vector<int> findClosestElements(vector<int>& arr,int k,int x) 
{
    std::vector<int> res;
    std::priority_queue<std::pair<int,int>> pq;

    for (auto it : arr)
    {
        int closest = abs(it - x);
        //std::cout << closest << " : " << it << "\n";
        pq.push(std::make_pair(closest,it));

        if (pq.size() > k)
        {
            pq.pop();     
        }
    }

    //std::cout << "\nDebug queue : \n";
    while(!pq.empty())
    {
        res.push_back(pq.top().second);
        //std::cout << pq.top().first << " : " << pq.top().second << "\n";
        pq.pop();
    }

    std::sort(res.begin(),res.end());
    return res;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。