Kth Largest Element II

来源:互联网 发布:加入农村淘宝要多少钱 编辑:程序博客网 时间:2024/06/06 12:26

Find K-th largest element in an array. and N is much larger than k.

 Notice

You can swap elements in the array

Example

In array [9,3,2,4,8], the 3rd largest element is 4.

In array [1,2,3,4,5], the 1st largest element is 52ndlargest element is 43rd largest element is 3 and etc.

解题思路:使用Heap的方式去做
java
public class Solution {    /*     * @param nums: an integer unsorted array     * @param k: an integer from 1 to n     * @return: the kth largest element     */    public int kthLargestElement2(int[] nums, int k) {        // write your code here        if (nums == null || nums.length == 0) {            return -1;        }        if (k > nums.length) {            return -1;        }        Queue<Integer> heap = new PriorityQueue<>();        for (int i = 0; i < nums.length; i++) {            heap.offer(nums[i]);            if (heap.size() > k) {                heap.poll();            }        }        return heap.peek();    }}


原创粉丝点击