zoukankan      html  css  js  c++  java
  • 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(); //取出顶部
        }
    }


  • 相关阅读:
    初探Remoting双向通信(三)
    MySQL主从复制
    MySQL锁机制
    mySql索引
    连接池
    JDBC
    数据库建表、约束、索引
    Oracle和SQL简介
    Stream API 和 注解
    lambda表达式
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10432752.html
Copyright © 2011-2022 走看看