题解 | #返回所有价格在 3美元到 6美元之间的产品的名称和价格#

寻找第K大

http://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf

import java.util.*;

public class Solution {
    public int findKth(int[] a, int n, int k) {
        //使用小根堆
        PriorityQueue<Integer> heap = new PriorityQueue<>(k);
        //先将k个元素放入堆中
        for(int i=0;i<k;i++){
            heap.add(a[i]);
        }
        for(int i=k;i<n;i++){
            if(heap.peek()<a[i]){
                heap.poll();
                heap.add(a[i]);
            }
        }
        
        return heap.peek();
    }
}
全部评论

相关推荐

06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务