Kth Largest Element

题目:

Find K-th largest element in an array.

分析:

partition的方法并不会做

解法:partition



解法:pQueue

class Solution {
    /*
     * @param k : description of k
     * @param nums : array of nums
     * @return: description of return
     */
    public int kthLargestElement(int k, int[] nums) {
        // write your code here
        if (nums.length < k) {
            throw new IndexOutOfBoundsException();
        }
        PriorityQueue<Integer> pQ = new PriorityQueue<Integer>();
        for(int i = 0; i < nums.length; i++) {
            if (pQ.size() < k) {
                pQ.offer(nums[i]);
            } else {
                if (pQ.peek() < nums[i]) {
                    pQ.poll();
                    pQ.offer(nums[i]);
                }
            }
        }
        return pQ.peek();
    }
};

results matching ""

    No results matching ""