215. Kth Largest Element in an Array java solutions

Posted Miller1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了215. Kth Largest Element in an Array java solutions相关的知识,希望对你有一定的参考价值。

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.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

1 public class Solution {
2     public int findKthLargest(int[] nums, int k) {
3         Arrays.sort(nums);
4         return nums[nums.length-k];
5     }
6 }

解法二:

维护一个大小为k 的最小堆,遍历一遍数组,再返回最小堆的顶部元素即为第k大元素。

 1 public class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         PriorityQueue<Integer> q = new PriorityQueue<Integer>(k+1);
 4         for(int n : nums){
 5             q.offer(n);
 6             if(q.size() > k) q.poll();
 7         }
 8         return q.poll();
 9     }
10 }

解法三: 又看到使用quickseleck 做的O(n),二刷再试下。

以上是关于215. Kth Largest Element in an Array java solutions的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-215. Kth Largest Element in an Array

#Leetcode# 215. Kth Largest Element in an Array

LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

LN : leetcode 215 Kth Largest Element in an Array

215. Kth Largest Element in an Array

215. Kth Largest Element in an Array