刷着LeetCode,遇到了一道没有特别好头绪的题目,于是在此梳理一下思绪,掌握这道题。

Question

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.

Analysis

这道题是一道教科书式的题目,非常の经典。

解法一

先用最稳定最高效的排序算法对其进行排序,然后在从数组中获取第k大的数字。

Solution

解法一(Java)

1
2
3
4
5
6
7
public class Solution {
public int findKthLargest(int[] nums, int k) {
final int N = nums.length;
Arrays.sort(nums);
return nums[N - k];
}
}

Reference

Rotate Image #48 - LeetCode

LeetCode : Rotate Image #48 - Github