leetcode 215, 378 (kth element, priority queue)

本文介绍了如何使用优先队列解决LeetCode中的两个问题:215号题目中找到数组的第k大元素,以及378号题目中在有序矩阵中寻找第k小元素。通过实例演示了如何利用优先队列的特性优化搜索过程,特别强调了插入顺序对优先级队列的影响。
摘要由CSDN通过智能技术生成

 Solution for leetcode 215

https://leetcode.com/problems/kth-largest-element-in-an-array/

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue();
        for(int num : nums){
            pq.offer(num);
            if(pq.size() > k){
                pq.poll();
            }
        }
        return pq.poll();  
    }
}

Solution for leetcode 378

https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/

(another solution uses binary search)

note: The order matters for inserting into the priority queue. We need to pay attention to the special characteristics of the matrix (the element on the right and on the bottom are larger)

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[0] - b[0]);
        pq.offer(new int[]{matrix[0][0],0,0});
        int row = matrix.length;
        int col = matrix[0].length;
        boolean[][] visited = new boolean[row][col];         
        int count = 0;                 
        while(count < k - 1){
            count++;
            int[] cur = pq.poll();
            int x = cur[1];
            int y = cur[2];
            if(x + 1 < row && visited[x+1][y] == false){
                visited[x + 1][y] = true; 
                pq.offer(new int[]{matrix[x + 1][y], x + 1, y});
            }
            if(y + 1 < col && visited[x][y+1] == false){
                visited[x][y+1] = true;
                pq.offer(new int[]{matrix[x][y + 1], x, y + 1});
            } 
        }
        return pq.poll()[0];      
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值