Advertisement
Guest User

Untitled

a guest
May 26th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1. class Solution {
  2.    
  3.     static class Pair implements Comparable<Pair>{
  4.        
  5.         int i;
  6.         int val;
  7.         public Pair(int i, int val) {
  8.             this.i=i;
  9.             this.val=val;
  10.         }
  11.        
  12.         @Override
  13.         public int compareTo(Pair x) {
  14.             return this.val-x.val;
  15.         }
  16.        
  17.     }
  18.     public int kthSmallest(int[][] a, int k) {
  19.         int n = a.length;
  20.         int m = a[0].length;
  21.         ArrayList<Integer> A = new ArrayList<>();
  22.         int[] p = new int[n];
  23.         PriorityQueue<Pair> PQ = new PriorityQueue<>();
  24.         for(int i=0;i<n;i++) {
  25.             PQ.add(new Pair(i,a[i][0]));
  26.            
  27.         }
  28.        
  29.         while(A.size() < k){
  30.             Pair tmp = PQ.poll();
  31.             A.add(tmp.val);
  32.             p[tmp.i]++;
  33.             if(p[tmp.i] < m) {
  34.                 PQ.add(new Pair(tmp.i, a[tmp.i][p[tmp.i]]));
  35.             }
  36.         }
  37.        
  38.         return A.get(k-1);
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement