leetcode 632. Smallest Range

632Smallest 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.

1、算是比较标准的two point 问题

2、这种题都有一个hash表来判断两个指针的距离条件,

不满足的时候end指针走,

满足的时候求值,并且start指针走,直到走到不满足就停下。让end走。



bool compare(const pair& a, const pair& b)
{
    return a.first < b.first;
}

class Solution {
public:
    vector smallestRange(vector>& nums)
    {
        vector> all;
        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = 0; j < nums[i].size(); j++)
                all.push_back(make_pair(nums[i][j], i));
        }
        sort(all.begin(), all.end(), compare);
        
        int start = 0, end = 0;
        unordered_map hash;
        vector ret(1, 0);
        ret.push_back(INT_MAX);
        while (end < all.size())
        {
            while (end < all.size() && hash.size() < nums.size())   //说明还有没有包含的行
            {
                hash[all[end].second] ++;
                end ++;
            }
            
            //然后start指针往后移动
            while (start <= end && hash.size() == nums.size())
            {
                //进入循环 说明 满足了条件了。
                if (all[end - 1].first - all[start].first < ret[1] - ret[0] )
                {
                    ret[0] = all[start].first;
                    ret[1] = all[end - 1].first;
                }
                
                if ( (--hash[all[start].second]) == 0)
                    hash.erase(all[start].second);
                start ++;
            }
        }
        return ret;
    }
};


你可能感兴趣的:(leetcode)