leetcode 632. Smallest Range k个数组至少一个元素最小区间+典型移动窗口做法

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

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:
The given list may contain duplicates, so ascending order means >= here.
1 <= k <= 3500
-105 <= value of elements <= 105.

本题题意很简单,虽然是分开的k个list,但是可以合并到一起,然后做排序,使用移动窗口去做即可

按照k个链表做分类,然后使用map做计数,然后移动窗口,不断收缩窗口即可,很棒的题

本质上和本题leetcode 76. Minimum Window Substring 双指针 + Map + 移动窗口 是一样的做法

这道题十分的棒,很值得学习

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>

using namespace std;



class Solution 
{
public:
    vector<int> smallestRange(vector<vector<int>>& nums) 
    {
        vector<pair<int, int>> all;
        int kind = nums.size();
        for (int i = 0; i < kind; i++)
        {
            for (int a : nums[i])
                all.push_back(make_pair(a, i));
        }
        sort(all.begin(), all.end());

        map<int, int> mmp;
        vector<int> res = {INT_MAX,INT_MAX};
        int left = 0, count = 0 , minDiff = INT_MAX;
        for (int right = 0; right < all.size(); right++)
        {
            mmp[all[right].second] += 1;
            if(mmp[all[right].second] == 1)
                count++;

            while (count == kind && left <= right)
            {
                int diff = all[right].first - all[left].first;
                if (diff < minDiff)
                {
                    minDiff = diff;
                    res = { all[left].first , all[right].first};
                }
                else if (diff == minDiff && all[left].first < res[0])
                    res = { all[left].first , all[right].first };

                mmp[all[left].second] -= 1;
                if (mmp[all[left].second] == 0)
                    count--;
                left++;
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值