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));
            }
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章