Problem

Find K-th largest element in an 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 5, 2nd largest element is 4, 3rd largest element is 3 and etc.

Note

可以不要用太简单的方法。
什么和Arrays.sort()最接近?PriorityQueue.
An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
A priority queue does not permit null elements.
A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).

做一个大小为k的PriorityQueue,peek()到的最顶端元素是队列中最小的元素,那么PQ就像一个自动过滤掉比顶端元素更小元素并把内部所有元素进行排序的容器。先把它装满,再和队列顶端的数字比较,大的就替换掉,小的就continue。遍历完所有元素之后,顶部的数就是第k大的数。
熟悉PriorityQueue的操作,.add(), .peek(), .remove().

Solution

1.

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

2.

class Solution {
    public int kthLargestElement(int k, int[] nums) {
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(k);
        for (int num : nums) {
            if (queue.size() < k) {
                queue.add(num);
            } else if (queue.peek() < num) {
                queue.remove();
                queue.add(num);
            }
        }
        return queue.peek();
    }
}

linspiration
161 声望53 粉丝