美文网首页
ORID52 heap相关题目

ORID52 heap相关题目

作者: Wilbur_ | 来源:发表于2020-08-28 09:51 被阅读0次

378. Kth Smallest Element in a Sorted Matrix 解题报告

算法

为什么用这个算法?
这道题一开始真的没思路,所以跟着答案走了一遍。里面有一个思想很重要:从问题最简单的地方开始。
这道题问你在这个matrix里面第k小的数是多少,你要做的就是先从第1小的开始看。那么这个matrix既然已经从左到右,从上到下排好序了,那么左上角,也就是matrix[0][0] 肯定是最小的数。
这时候在找第二小的数字,那么只能是他右边或者下边的数,因为已经排好序了。
重复这个步骤,直到k次
那么heap就可以解决这个问题,你用minHeap来把最小的放到最前面,然后依次把最小的取出(因为你要第k小的数字)
每取出一次数之后,就把他右边或者下边最小的数放到这个堆里面。(这一步代码里面比较难实现,所以要练习)
做完k次循环之后,直接取heap里面第一个数的值就可以了。

代码实现

有什么要注意的地方?

class Solution {
    public class Pair {
        int x, y, val;
        public Pair(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }
    }
    class PairComparator implements Comparator<Pair> {
        public int compare(Pair a , Pair b) {
            return a.val - b.val;
        }
    }
    public int kthSmallest(int[][] matrix, int k) {
        int[] dx = new int[] {0, 1};
        int[] dy = new int[] {1, 0};
        int n = matrix.length;
        int m = matrix[0].length;
        boolean[][] hash = new boolean[n][m];
        PriorityQueue<Pair> minHeap = new PriorityQueue<Pair>(k, new PairComparator());
        minHeap.add(new Pair(0, 0, matrix[0][0]));
        for (int i = 1; i < k; i++) {
            Pair cur = minHeap.poll();
            for (int j = 0; j < 2; j++) {
                int next_x = cur.x + dx[j];
                int next_y = cur.y + dy[j];
                Pair next_pair = new Pair(next_x, next_y, 0);
                if (next_x < n && next_y < m && !hash[next_x][next_y]) {
                    hash[next_x][next_y] = true;
                    next_pair.val = matrix[next_x][next_y];
                    minHeap.add(next_pair);
                }
            }
        }
        return minHeap.peek().val;
    }
}

时间空间复杂度

O(klogn)

哪些相关题目做过的?

相关文章

  • ORID52 heap相关题目

    378. Kth Smallest Element in a Sorted Matrix 解题报告 算法 为什么用...

  • JVM Flags介绍-Heap相关

    前言 此篇文章是关于Userful JVM Flags系列2和系列4的总结 JVM flag类别 标准flags,...

  • Promise相关题目

    实现一个person对象,有eat和dinner两种方法请用实例【依次类推】new Person('Tom').s...

  • 图相关题目

    Minimum Height TreesFor a undirected graph with tree char...

  • web相关题目

    你觉得前端工程师的价值体现在哪? 为简化用户使用提供技术支持(交互部分) 为多个浏览器兼容性提供支持 为提高用户浏...

  • GCD相关题目

    1、以下代码结果会如何? 结果如下: 会造成死锁,主线程中【同步执行+主队列】,造成的互相等待。 2、写一个线程安...

  • Array篇easy难度之矩阵行值加在一起排序

    关键词 二分查找,Heap,PriorityQueue 题目描述 https://leetcode.com/pro...

  • ART Runtime创建(三)--Heap的创建

    Heap的创建位于/art/runtime/runtime.cc的Runtime::Init方法中 一. 相关知识...

  • [性能调优] out of memory :Heap space

    题目其实取大了…… 背景:线上环境java服务报错,异常如题out of memory :Heap space环境...

  • 二叉堆

    二叉堆(Binary Heap) 本文相关代码参见 Algorithms/BinaryHeap 定义 二叉堆本质上...

网友评论

      本文标题:ORID52 heap相关题目

      本文链接:https://www.haomeiwen.com/subject/oziwjktx.html