LintCode 543: Kth Largest in N Arrays (maxHeap Classic title)

  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

Solution 1:
Each array in descending order, each array index pointing to a beginning, and then one by one pick each array of index values pointing into maxHeap, while index ++. After doing so the k-th, k-th into maxHeap is the desired value.
code show as below:

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));
            }
        }
    }
};
发布了577 篇原创文章 · 获赞 21 · 访问量 8万+

Guess you like

Origin blog.csdn.net/roufoo/article/details/102996791