• 215. Kth Largest Element in an Array【Medium】【找到第 k 大的元素】


    Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

    Example 1:

    Input: [3,2,1,5,6,4] and k = 2
    Output: 5
    

    Example 2:

    Input: [3,2,3,1,2,4,5,5,6] and k = 4
    Output: 4

    Note: 
    You may assume k is always valid, 1 ≤ k ≤ array's length.

    Accepted
    321,865
    Submissions
    702,362
     
     
     Queue接口与List、Set同一级别,都是继承了Collection接口。LinkedList实现了Queue接 口。Queue接口窄化了对LinkedList的方法的访问权限
    (即在方法中的参数类型如果是Queue时,就完全只能访问Queue接口所定义的方法 了,而不能直接访问 LinkedList的非Queue的方法),
    以使得只有恰当的方法才可以使用。BlockingQueue 继承了Queue接口。 add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常 remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常 element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常 offer 添加一个元素并返回true 如果队列已满,则返回false poll 移除并返问队列头部的元素 如果队列为空,则返回null peek 返回队列头部的元素 如果队列为空,则返回null put 添加一个元素 如果队列满,则阻塞 take 移除并返回队列头部的元素 如果队列为空,则阻塞

      

    class Solution {
        public int findKthLargest(int[] nums, int k) {
            Arrays.sort(nums);
            return nums[nums.length - k];
        }
    }


    class Solution {
        public int findKthLargest(int[] nums, int k) {  //堆排序
            PriorityQueue<Integer> pq = new PriorityQueue<>(); 
            for (int val : nums) {
                pq.offer(val); 
                if(pq.size() > k) 
                    pq.poll(); //删除顶部
            }
            return pq.peek(); //取出顶部
        }
    }


  • 相关阅读:
    Azure虚拟机部署Linux+PHP+Swoole
    [经验分享]OBS 如何实现多路推流
    SQL Server 中的登陆用户如何只看到指定的数据库
    NCF 数据库错位导致站点访问不了
    AutoIT+Selenium的使用
    2019年入职体检那些事
    Jmeter 针对工具类的每个方法进行测试
    Effective Jmeter:记录一些场景下有效的解决方案
    通过 Test Fragment + Module Controller 封装登录接口
    在setUp线程组中初始化全局工具类
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10432752.html
Copyright © 2020-2023  润新知