632. Smallest Range
代码
#include<vector> #include<unordered_map> #include<iostream> using namespace std; class Solution { public: vector<int> smallestRange(vector<vector<int>>& nums) { vector<int> res; vector<pair<int,int>> v; unordered_map<int,int> m; for(int i=0;i<nums.size();++i){ for(int num: nums[i]){ v.push_back({num,i}); } } sort(v.begin(),v.end()); cout<<endl; int left=0,n=v.size(),k=nums.size(),cnt=0, diff=INT_MAX; for(int right=0;right<n;++right){ if(m[v[right].second]==0) ++cnt; ++m[v[right].second]; while(cnt==k){ //cout<<"left: "<<left<<" right: "<<right<<endl; if(diff>v[right].first-v[left].first){ diff=v[right].first-v[left].first; res={v[left].first, v[right].first}; } if(m[v[left].second]==1) --cnt; m[v[left].second]--; left++; } } return res; } }; int main(){ Solution s; vector<vector<int>> nums={{4,10,15,24,26}, {0,9,12,20}, {5,18,22,30}}; vector<int> res=s.smallestRange(nums); }