knakul853

Untitled

Jul 19th, 2020
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4.  
  5. class Solution {
  6. public:
  7.     int kthSmallest(vector<vector<int>>& matrix, int k) {
  8.        
  9.        int n = (int)matrix[0].size();
  10.         int m = (int)matrix[0].size();
  11.        
  12.         priority_queue<int, vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>>>pq;
  13.        
  14.         for(int i=0;i<n;i++)
  15.         {
  16.             pq.push({matrix[i][0],{i, 0}});
  17.         }
  18.         int ans = 0;
  19.        
  20.         while(k--)
  21.         {
  22.             auto node = pq.top();
  23.             int j = node.second.second;
  24.             int i = node.second.first;
  25.             ans = node.first;
  26.             pq.pop();
  27.            
  28.             if(j+1<m)
  29.             {
  30.                 pq.push({matrix[i][j+1], {i, j+1}});
  31.             }
  32.         }
  33.        
  34.         return ans;
  35.     }
  36. };
Add Comment
Please, Sign In to add comment