• [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;
        }
    }
  • 相关阅读:
    puppeteer 离线安装chromium
    如何在Taro项目中使用Iconfont(阿里图标)
    POI3.8内存中限制行数为100问题记录
    centos下puppeteer调用chromium报错,缺少包
    VS Code 简单配置运行Java
    使用VSCode 断点调试 js项目,html页面
    Java--Excel--poi 边框、单元格换行、 背景色、合并单元格相关
    浅析Spring Aware
    Spring MVC 注解
    异常处理
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9800363.html
Copyright © 2020-2023  润新知