[Leetcode] 632. Smallest Range 解题报告

题目

You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the klists.

We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.

Example 1:

Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
Output: [20,24]
Explanation: 
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].

Note:

  1. The given list may contain duplicates, so ascending order means >= here.
  2. 1 <= k <= 3500
  3. -105 <= value of elements <= 105.
  4. For Java users, please note that the input type has been changed to List>. And after you reset the code template, you'll see this point.

思路

题目有点类似于[Leetcode] 23. Merge k Sorted Lists 解题报告。我们首先将nums中每一列的最小数字都加入队列中,这形成的一定是一个合法的range(只不过不一定是最小的range)。然后找出队列头部的元素,试图将其取出,并将其所在列的下一个元素(如果有的话)加入队列。这样就保证了队列中始终存在每一行中的某一个元素,保证了range的合法性。此时更新一下range。当队列的头部元素已经是某行的最后一个元素时,说明我们无法再更新range了,此时返回当前的smallest range即可。

我们在优先队列中存储迭代器以简化运算。算法的时间复杂度是O(n),其中n是nums中所有元素的个数。空间复杂度是O(r),其中r是nums中的行个数。

代码

class Solution {
public:
    vector smallestRange(vector>& nums) {
        int lo = INT_MAX, hi = INT_MIN;
        priority_queue, vector>, comp> pq;
        for (auto &row : nums) {        // add the first element of each row to pq
            lo = min(lo, row[0]), hi = max(hi, row[0]);
            pq.push({row.begin(), row.end()});
        }
        vector ans = {lo, hi};
        while (true) {                  // update the values in one row
            auto p = pq.top();
            pq.pop();
            ++p.first;
            if (p.first == p.second) {
                break;
            }
            pq.push(p);
            lo = *pq.top().first;
            hi = max(hi, *p.first);
            if (hi - lo < ans[1] - ans[0]) {
                ans = {lo, hi};
            }
        }
        return ans;
    }
private:
    typedef vector::iterator vi;
    struct comp {
        bool operator()(pair p1, pair p2) {
            return *p1.first > *p2.first;
        }
    };
};

你可能感兴趣的:(IT公司面试习题)