zoukankan      html  css  js  c++  java
  • [LeetCode] 378. Kth Smallest Element in a Sorted Matrix

    Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

    Note that it is the kth smallest element in the sorted order, not the kth distinct element.

    Example:

    matrix = [
       [ 1,  5,  9],
       [10, 11, 13],
       [12, 13, 15]
    ],
    k = 8,
    
    return 13.
    

    Note: 
    You may assume k is always valid, 1 ≤ k ≤ n2.

    题意:给一个已经排好序的二维数组,找到第k小的数

    注意,它不是蛇形有序的。

    法一:使用堆,一边插一边删,保证堆只有k个元素就行了;

    class Solution {
        public int kthSmallest(int[][] matrix, int k) {
            int n = matrix.length;
            PriorityQueue<Integer> heap = new PriorityQueue<>(k + 1, (a, b) -> {
                if (a < b)
                    return 1;
                if (a > b)
                    return -1;
                else
                    return 0;
            });
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++) {
                    heap.add(matrix[i][j]);
                    if (heap.size() > k)
                        heap.poll();
                }
            return heap.poll();
        }
    }

    法二:其实用法一有个特点,我们没有利用排好序的这个特点,换言之,随便给个二维数组,就可以实现,显然不可能是最高效的

    既然想到是排好序的,那么又是查,我们就会想到二分的思想

    class Solution {
        private int helper(int[][] matrix, int tar) {
            int n = matrix.length;
            int i = n - 1;
            int j = 0;
            int res = 0;
            while (i >= 0 && j < n) {
                if (matrix[i][j] <= tar) {
                    res += i + 1;
                    j++;
                } else {
                    i--;
                }
            }
            return res;
        }
        public int kthSmallest(int[][] matrix, int k) {
            int n = matrix.length;
            int left = matrix[0][0];
            int right = matrix[n - 1][n - 1];
            while (left < right) {
                int mid = left + (right - left) / 2;
                int cnt = helper(matrix, mid);
                if (cnt < k)
                    left = mid + 1;
                else
                    right = mid;
            }
            return left;
        }
    }
  • 相关阅读:
    久未更 ~ 四之 —— Vsftpd出现 Failed to start Vsftpd ftp daemon错误
    久未更 ~ 三之 —— CardView简单记录
    久未更 ~ 二之 —— TextView 文字省略
    久未更 ~ 一之 —— 关于ToolBar
    【UVA1636】决斗Headshot
    【NOIP模拟】花园
    【UVA1262】Password
    【UVA10820】交表
    【UVA1635】哑元
    【UVA12716】GCD和XOR
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9800363.html
Copyright © 2011-2022 走看看