Leetcode 215. Kth Largest Element in an Array

来源:互联网 发布:淘宝如何清空收藏夹 编辑:程序博客网 时间:2024/06/03 17:30

215. Kth Largest Element in an Array

Total Accepted: 81842 Total Submissions: 226913 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.

Hide Company Tags
 Facebook Amazon Microsoft Apple Bloomberg Pocket Gems
Hide Tags
 Heap Divide and Conquer
Hide Similar Problems
 (M) Wiggle Sort II (M) Top K Frequent Elements

思路:

看到top kth,直接反应就是heap。

用一个最大堆,然后放入元素,第K次取的元素就是所求。

运行时间:16ms。

public class Solution {    public int findKthLargest(int[] nums, int k) {        PriorityQueue<Integer> heap = new PriorityQueue<Integer>(Collections.reverseOrder());        for(int item : nums) heap.offer(item);                int count = 0;        while(count < k){            int item = heap.poll();            count++;            if(count == k) return item;        }        return -1;    }}

然后一看标签是分治。那好现在nums的k,就等于nums删除最大元素的k -1,直到k==1。

于是最后一定是最大元素。于是一定要sort。那么sort之后直接无视分治取出相应位置元素就可以了。

运行时间:5ms。

public class Solution {    public int findKthLargest(int[] nums, int k) {        Arrays.sort(nums);        return nums[nums.length - k];    }}

0 0
原创粉丝点击