knakul853

Untitled

Jun 18th, 2020
144
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. class Solution {
  5. public:
  6.     int kthSmallest(vector<vector<int>>& matrix, int k) {
  7.        
  8.        int n = (int)matrix[0].size();
  9.         int m = (int)matrix[0].size();
  10.        
  11.         priority_queue<int, vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>>>pq;
  12.        
  13.         for(int i=0;i<n;i++)
  14.         {
  15.             pq.push({matrix[i][0],{i, 0}});
  16.         }
  17.         int ans = 0;
  18.        
  19.         while(k--)
  20.         {
  21.             auto node = pq.top();
  22.             int j = node.second.second;
  23.             int i = node.second.first;
  24.             ans = node.first;
  25.             pq.pop();
  26.            
  27.             if(j+1<m)
  28.             {
  29.                 pq.push({matrix[i][j+1], {i, j+1}});
  30.             }
  31.         }
  32.        
  33.         return ans;
  34.     }
  35. };
Add Comment
Please, Sign In to add comment