[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<List<Integer>>. 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<int> smallestRange(vector<vector<int>>& nums) {
        int lo = INT_MAX, hi = INT_MIN;
        priority_queue<pair<vi, vi>, vector<pair<vi, vi>>, 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<int> 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<int>::iterator vi;
    struct comp {
        bool operator()(pair<vi, vi> p1, pair<vi, vi> p2) {
            return *p1.first > *p2.first;
        }
    };
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值