Advertisement
nikunjsoni

632

Apr 13th, 2021
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     typedef vector<int>::iterator vi;
  4.     struct compare{
  5.         bool operator()(const pair<vi, vi>& a, const pair<vi, vi>& b){
  6.             return *(a.first) > *(b.first);
  7.         }
  8.     };
  9.    
  10.     vector<int> smallestRange(vector<vector<int>>& nums) {
  11.         priority_queue<pair<vi, vi>, vector<pair<vi, vi>>, compare> pq;
  12.        
  13.         int low = INT_MAX, high=INT_MIN;
  14.         for(auto &row : nums){
  15.             low = min(low, row[0]);
  16.             high = max(high, row[0]);
  17.             pq.push({row.begin(), row.end()});
  18.         }
  19.         vector<int> ans = {low, high};
  20.        
  21.         while(true){
  22.             auto ptr = pq.top();
  23.             pq.pop();
  24.             ++ptr.first;
  25.             if(ptr.first == ptr.second) break;
  26.             pq.push(ptr);
  27.             auto top = pq.top();
  28.             low = *(top.first);
  29.             high = max(high, *(ptr.first));
  30.            
  31.             if(high-low < ans[1]-ans[0]){
  32.                 ans[1] = high;
  33.                 ans[0] = low;
  34.             }
  35.         }
  36.         return ans;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement