码迷,mamicode.com
首页 > 其他好文 > 详细

215. Kth Largest Element in an Array

时间:2015-11-22 13:51:04      阅读:110      评论: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.

链接: http://leetcode.com/problems/kth-largest-element-in-an-array/
题解:

找数组中第k大的元素,可以用heap,Radix sort或者Quick-Select。不过Quick-Select的Time Compleixty只有在Amorized analysis上才是O(n)。下面是使用Java自带的priority queue min-heap来完成的,算是投机取巧了。二刷要补上Radix sort以及Quick-Select

Time Complexity - O(nlogn), Space Complexity - O(k)

public class Solution {
    public int findKthLargest(int[] nums, int k) {   // use min oriented heap,  store min value at top of the heap
        if(nums == null || nums.length == 0)
            return 0;
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k);
        
        for(int i = 0; i < nums.length; i++) {
            if(pq.size() < k)
                pq.offer(nums[i]);
            else {
                if(nums[i] > pq.peek()) {
                    pq.poll();              // remove min
                    pq.offer(nums[i]);
                }
            }
        }
        
        return pq.poll();
    }
}

 

Reference:

https://leetcode.com/discuss/38336/solutions-partition-priority_queue-multiset-respectively

https://leetcode.com/discuss/45627/ac-clean-quickselect-java-solution-avg-o-n-time

https://leetcode.com/discuss/36913/solutions-java-having-worst-time-complexity-with-explanation

https://leetcode.com/discuss/36991/java-quick-select

215. Kth Largest Element in an Array

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/4982861.html

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