LeetCode 378: Kth Smallest Element in Sorted Matrix

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 378: Kth Smallest Element in Sorted Matrix相关的知识,希望对你有一定的参考价值。

1. Use priority queue. Need to check whether one element has been double counted:

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        if (matrix.length == 0 || matrix[0].length == 0) return 0;
        PriorityQueue<int[]> queue = new PriorityQueue<>((n1, n2) -> n1[0] - n2[0]);
        queue.offer(new int[]{matrix[0][0], 0, 0});
        int i = 1;
        int[] current = new int[3];
        Set<Integer> visited = new HashSet<>();
        while (!queue.isEmpty() && i++ <= k) {
            current = queue.poll();
            if (current[1] < matrix.length - 1 && !visited.contains((current[1] + 1)*matrix[0].length + current[2])) {
                queue.offer(new int[] {matrix[current[1] + 1][current[2]], current[1] + 1, current[2]});
                visited.add((current[1] + 1)*matrix[0].length + current[2]);
            }
            if (current[2] < matrix[0].length - 1 && !visited.contains(current[1]*matrix[0].length + current[2] + 1)) {
                queue.offer(new int[] {matrix[current[1]][current[2] + 1], current[1], current[2] + 1});
                visited.add(current[1] * matrix[0].length + current[2] + 1);
            }
        }
        return current[0];
    }
}

 

 

2 Binary search: For this kind of matrix, binary search should work as counting how many number satify the condition for each column and row.

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        if (matrix.length == 0 || matrix[0].length == 0) return 0;
        int start = matrix[0][0], end = matrix[matrix.length - 1][matrix[0].length - 1];
        while (start < end) {
            int mid = start + (end - start) / 2;
            int count = 0, j = matrix[0].length - 1;
            for (int i = 0; i < matrix.length; i++) {
                while (j >= 0 && matrix[i][j] > mid) j--;
                count += j + 1;
            }
            
            if (count < k) start = mid + 1;
            else end = mid;
        }
        return start;
    }
}

 

以上是关于LeetCode 378: Kth Smallest Element in Sorted Matrix的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 378. Kth Smallest Element in a Sorted Matrix

Leetcode378. Kth Smallest Element in a Sorted Matrix

LeetCode 378: Kth Smallest Element in Sorted Matrix

Leetcode:378. Kth Smallest Element in a Sorted Matrix

leetcode 378. Kth Smallest Element in a Sorted Matrix

378. Kth Smallest Element in a Sorted Matrix