• [LC] 215. Kth Largest Element in an Array


    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.

    Solution 1: 

    Time: O(NlgN)

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

    Solution 2:

    Time: O(Nlgk)

    class Solution {
        public int findKthLargest(int[] nums, int k) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            PriorityQueue<Integer> pq = new PriorityQueue<>();
            for (int num : nums) {
                pq.offer(num);
                if (pq.size() > k) {
                    pq.poll();
                }
            }
            return pq.poll();
        }
    }
  • 相关阅读:
    高维协方差矩阵估计
    互信息
    投资组合模型
    R语言
    sklearn
    Python学习
    swagger使用过程中遇到的坑
    mysql杂文
    2018狗年,半年报
    Springboot 手动搭建项目 --redis配置&日志完善+用户名
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11879712.html
Copyright © 2020-2023  润新知