LintCode 1566: Minimum Difference (MinHeap 经典难题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/84989549

原题如下:
1566. Minimum Difference
Given a 2D array size of n * m and the elements of each row of the array are sorted. Select 1 number from each row and select n numbers in total. And the diff of n numbers is maximum-minimum, find the minimum diff.

Example
Input: [[1,2,3,4,5],[6,7,8,9,10]]
Output: 1

这题感觉不容易。我的解法是用minHeap。首先将每行的第一个元素拿出来建最小堆。然后看最小堆的元素是从哪一行来的,则pop top(), 并将该行的下一个元素进堆。注意这时候要更新minHeap的最大值和minDiff。
注意,这个minDiff要用绝对值
当某一行的元素走到头之后,就可退出循环,返回minDiff即可。

下面这个链接我感觉不错,不过这个是基于两个排序数组的,方法类似。
https://prismoskills.appspot.com/lessons/Arrays/Find_closest_elements_in_2_arrays.jsp

不知道还有没有更高效的方法呢。


struct Node {
    int val;
    int rowIndex;
    int colIndex;
    Node(int v = 0, int r = 0, int c = 0) : val(v), rowIndex(r), colIndex(c) {} 
    friend bool operator > (const Node &a, const Node &b);
    friend bool operator < (const Node &a, const Node &b);
    friend bool operator == (const Node &a, const Node &b);
};
    
inline bool operator > (const Node &a, const Node &b) {
    return a.val > b.val;
}
    
inline bool operator < (const Node &a, const Node &b) {
    return a.val < b.val;
}
    
inline bool operator == (const Node &a, const Node &b) {
    return a.val == b.val;
}


class Solution {
public:
    /**
     * @param array: a 2D array
     * @return: the minimum difference
     */
 
    int minimumDifference(vector<vector<int>> &array) {
        int rLen = array.size();
        if (rLen == 0) return 0;
        
        int cLen = array[0].size();
        
        priority_queue<Node, vector<Node>, greater<Node>> pq;  //min-Heap

        int minV = INT_MAX;
        int maxV = INT_MIN;
        int minDiff = INT_MAX;
        const int totalCount = rLen * cLen;
        
        for (int r = 0; r < rLen; ++r) {
            pq.push(Node(array[r][0], r, 0));
            maxV = max(maxV, array[r][0]);
        }
        minDiff = min(minDiff, abs(maxV - pq.top().val));
        int count = rLen;
        vector<int> pointers(rLen, 1);
        
        while(count <= totalCount) { 
            int rowIndex = pq.top().rowIndex;
            
            if (pointers[rowIndex] < cLen - 1) pointers[rowIndex]++;
            else break;
            
            Node candidate = Node(array[rowIndex][pointers[rowIndex]], 
                                   rowIndex, 
                                   pointers[rowIndex]);
            
            maxV = max(maxV, candidate.val);
            pq.pop();
            pq.push(candidate);
            int newDiff = abs(maxV - pq.top().val);
            minDiff = min(minDiff, newDiff);
            count++;
        }   
        
        return minDiff;
    }
};

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/84989549