LintCode 543: Kth Largest in N Arrays (maxHeap经典题)

  1. Kth Largest in N Arrays
    中文English
    Find K-th largest element in N arrays.

Example
Example 1:

Input:
k=3, [[9,3,2,4,7],[1,2,3,4,8]]
Output:
7
Explanation:
the 3rd largest element is 7

Example 2:

Input:
k = 2, [[9,3,2,4,8],[1,2,3,4,2]]
Output:
8
Explanation:
the 1st largest element is 9, 2nd largest element is 8, 3rd largest element is 4 and etc.

Notice
You can swap elements in the array

解法1:
每个array从大到小排序,每个array一个index指向开头,然后挨个挑每个array的index指向的值入maxHeap,同时index++。如此操作k次后,第k次入maxHeap的值就是所求。
代码如下:

struct Node {
    int value;
    int fromArray;
    int index;
    Node (int v = 0, int f = 0, int i = 0) : value(v), fromArray(f), index(i) {}
};

struct cmp {
    bool operator() (const Node &a, const Node &b) {
        return a.value < b.value;  //maxHeap
    }
};

class Solution {
public:
    /**
     * @param arrays: a list of array
     * @param k: An integer
     * @return: an integer, K-th largest element in N arrays
     */
    int KthInArrays(vector<vector<int>> &arrays, int k) {
        int n = arrays.size();
        
        priority_queue<Node, vector<Node>, cmp> maxHeap;
        for (int i = 0; i < n; ++i) {
            if (arrays[i].size() > 0) {
                sort(arrays[i].begin(), arrays[i].end(), greater<int>());
                maxHeap.push(Node(arrays[i][0], i));
            }
        }
        int count = 0;
        while(maxHeap.size() > 0) {
            Node topNode = maxHeap.top();
            count++;
            if (count == k) return topNode.value;
            
            maxHeap.pop();
            if (topNode.index < arrays[topNode.fromArray].size() - 1) {
                maxHeap.push(Node(arrays[topNode.fromArray][topNode.index + 1], topNode.fromArray, topNode.index + 1));
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值