Leetcode 215. Kth Largest Element in an Array

来源:互联网 发布:node.js实战 第1季 编辑:程序博客网 时间:2024/06/04 18:55

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.

Analysis: I can use the heap sort to sort for the element, the priority queue is the heap implmentation

//Here is the heap implementation 

http://algs4.cs.princeton.edu/24pq/


public class Solution {    public int findKthLargest(int[] nums, int k) {      PriorityQueue<Integer> queue = new PriorityQueue<Integer>();      int length = nums.length;      for(int i = 0; i < length; i++){        if(queue.size() < k)          queue.add(nums[i]);        else if( queue.peek() < nums[i]){          queue.remove();          queue.add(nums[i]);        }      }      return queue.peek();    }}





0 0
原创粉丝点击