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 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个数组,问找到最小的一个范围[a,b],使得每一个数组当中至少有一个元素落入这个区间。
思路:
这道题将会用到贪心的思想,首先假设k个数组满足一下条件
[a01,a02,a03,a04……]
[a11,a12,a13,a14……]
……
[ak1,ak2,ak3,ak4……]
假设存在a01
vector<int> smallestRange(vector<vector<int>>& nums) {
typedef vector<int>::iterator vi;
struct comp {
bool operator()(pair<vi, vi> p1, pair<vi, vi> p2) {
return *p1.first > *p2.first;
}
};
int lo = INT_MAX, hi = INT_MIN;
priority_queue<pair<vi, vi>, vector<pair<vi, vi>>, comp> pq;
for (auto &row:nums){
lo = min(lo,row[0]);
hi = max(hi,row[0]);
pq.push({row.begin(),row.end()});
}
vector<int> ans = {lo, hi};
while(true){
auto num =pq.top();
pq.pop();
num.first++;
if(num.first==num.second){
break;
}
pq.push(num);
lo = *pq.top().first;
if(*num.first>hi) hi =*num.first;
if(hi-lo<ans[1]-ans[0]){
ans[0]=lo;
ans[1]=hi;
}
}
return ans;
}