- 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));
}
}
}
};