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

LeetCode:Kth Largest Element in an Array

时间:2016-06-12 02:01:21      阅读:126      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!