码迷,mamicode.com
首页 > 编程语言 > 详细

215. Kth Largest Element in an Array java solutions

时间:2016-07-04 17:07:45      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5640946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!