package leetcode;

/**
 * https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
 */
public class Problem378 {
    public int kthSmallest(int[][] matrix, int k) {
        int rowSize = matrix.length;
        int colSize = matrix[0].length;
        int row = (k - 1) / rowSize;
        int col = (k - 1) - (row * colSize);
        // TODO
        return matrix[row][col];
    }

    public static void main(String[] args) {
        Problem378 prob = new Problem378();
        for (int i = 0; i < 9; i++) {
            System.out.println(prob.kthSmallest(new int[][]{
                {1, 5, 9},
                {10, 11, 13},
                {12, 13, 15}
            }, i + 1));
        }

        for (int i = 0; i < 4; i++) {
            System.out.println(prob.kthSmallest(new int[][]{
                {1, 2},
                {1, 3},
            }, i + 1));
        }

        for (int i = 0; i < 4; i++) {
            System.out.println(prob.kthSmallest(new int[][]{
                {1, 1, 1},
                {1, 1, 3},
                {1, 2, 3},
            }, i + 1));
        }
    }
}

@@ -12,16 +12,49 @@
 tcode;%0A%0A
+import java.util.PriorityQueue;%0A%0A
 /**%0A * h
@@ -217,524 +217,116 @@
     
-int rowSize = matrix.length;%0A        int colSize = matrix%5B0%5D.length;%0A        int row = (k - 1) / rowSize;%0A        int col = (k - 1) - (row * colSize);%0A        // TODO%0A        return matrix%5Brow%5D%5Bcol%5D;%0A    %7D%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem378 prob = new Problem378();%0A        for (int i = 0; i %3C 9; i++) %7B%0A            System.out.println(prob.kthSmallest(new int%5B%5D%5B%5D%7B%0A                %7B1, 5, 9%7D,%0A                %7B10, 11, 13%7D,%0A                %7B12, 13, 15%7D%0A            %7D, i + 1));%0A    
+PriorityQueue%3CInteger%3E queue = new PriorityQueue%3C%3E();%0A        for (int i = 0; i %3C matrix.length; i++) %7B%0A
     
-%7D%0A%0A
     
@@ -334,39 +334,54 @@
    for (int 
-i
+j
  = 0; 
-i %3C 4; i
+j %3C matrix%5Bi%5D.length; j
 ++) %7B%0A      
@@ -390,139 +390,84 @@
     
-System.out.println(prob.kthSmallest(new int%5B%5D%5B%5D%7B%0A                %7B1, 2%7D,%0A                %7B1, 3%7D,%0A            %7D, i + 1));%0A        %7D%0A
+    queue.add(matrix%5Bi%5D%5Bj%5D);%0A            %7D%0A        %7D%0A        int result = 0;
 %0A   
@@ -495,9 +495,9 @@
 i %3C 
-4
+k
 ; i+
@@ -517,171 +517,65 @@
     
-System.out.println(prob.kthSmallest(new int%5B%5D%5B%5D%7B%0A                %7B1, 1, 1%7D,%0A                %7B1, 1, 3%7D,%0A                %7B1, 2, 3%7D,%0A            %7D, i + 1));%0A        %7D
+result = queue.remove();%0A        %7D%0A        return result;
 %0A   

Update problem 378