博客
关于我
LeetCode 378.有序矩阵中第K小的元素
阅读量:246 次
发布时间:2019-03-01

本文共 1954 字,大约阅读时间需要 6 分钟。

为了找到n x n矩阵中按升序排列的第k小的元素,我们可以采用最小堆来维护候选集合。每次从堆中取出最小的元素,然后将其右边和下边的元素加入候选集合,同时记录已经访问过的位置以避免重复处理。这种方法确保了每次处理的元素都是当前最小的,从而能够正确找到第k小的元素。

方法思路

  • 初始化优先队列:将矩阵的左上角元素(0,0)作为初始元素,加入优先队列。
  • 访问记录数组:创建一个二维数组visited,记录每个位置是否已经被访问过。
  • 处理优先队列:每次从优先队列中取出最小的元素,计数器加1。如果计数器等于k,则返回该元素的值。
  • 扩展相邻元素:对于取出的元素,扩展其右边和下边的位置。如果这些位置在矩阵范围内且未被访问过,则将它们加入优先队列,并标记为已访问。
  • 这种方法利用了优先队列按顺序处理元素的特点,确保每次处理的都是当前最小的元素,从而能够正确找到第k小的元素。

    解决代码

    import java.util.*;class Solution {    class Node {        int x;        int y;        int val;        Node(int x, int y, int val) {            this.x = x;            this.y = y;            this.val = val;        }    }    class NodeComparator implements Comparator
    { public int compare(Node a, Node b) { return a.val - b.val; } } public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; if (n == 0) { return 0; } int[] cx = {0, 1}; int[] cy = {1, 0}; boolean[][] visited = new boolean[n][n]; PriorityQueue
    minHeap = new PriorityQueue<>(k, new NodeComparator()); Node start = new Node(0, 0, matrix[0][0]); minHeap.add(start); visited[0][0] = true; int count = 0; while (!minHeap.isEmpty()) { Node node = minHeap.poll(); count++; if (count == k) { return matrix[node.x][node.y]; } for (int i = 0; i < 2; i++) { int x = node.x + cx[i]; int y = node.y + cy[i]; if (x < n && y < n && !visited[x][y]) { visited[x][y] = true; minHeap.add(new Node(x, y, matrix[x][y])); } } } return 0; }}

    代码解释

    • Node类:用于存储当前处理的位置及其对应的矩阵值。
    • NodeComparator:用于比较节点的大小,确保优先队列按值顺序处理。
    • kthSmallest方法:主要逻辑函数,实现找到第k小的元素。
      • 初始化:将起点加入优先队列,并标记为已访问。
      • 优先队列处理:每次取出最小的元素,检查是否是第k小的。
      • 扩展相邻元素:处理当前元素的右边和下边位置,避免越界和重复访问。

    这种方法通过利用优先队列和访问记录,确保高效地找到矩阵中的第k小的元素。

    转载地址:http://rtvv.baihongyu.com/

    你可能感兴趣的文章
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘html-webpack-plugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed with exit code: 1
    查看>>