首页 > 其他 > 详细

LeetCode:Kth Largest Element in an Array

时间:2016-06-12 02:01:13      阅读:182      评论:0      收藏:0      [点我收藏+]

Kth Largest Element in an Array




Total Accepted: 59659 Total Submissions: 175932 Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
 Heap Divide and Conquer






















思路:

将nums中的前k个元素建一个“大根”堆,然后将后面[k+1,n]元素于堆顶进行比较。比堆项大,则交换、重建堆。

时间复杂度 = 第一次建堆时间 + (n-k)建堆时间(即最坏情况每次都要交换、建堆) = logk + (n-k)logk = (n-k+1)logk


java code:

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
        for(int num : nums) {
            queue.offer(num);
            if(queue.size() > k) queue.poll();
        }
        return queue.peek();
    }
}


LeetCode:Kth Largest Element in an Array

原文:http://blog.csdn.net/itismelzp/article/details/51636372

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!