LeetCode题解专栏:LeetCode题解
我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java和Python的解法都有。
题目地址:Kth Largest Element in an Array - LeetCode
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.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
这道题目是经典的求数组第K大元素的题目。
最坏的解法是先排序,再找。时间复杂度是 O(NlogN)。
好一些的办法是使用最大堆进行排序,时间复杂度是O(NlogK)。
另外一种做法是使用Quickselect
,但是最坏的时间复杂度跟快排一样是N^2,我就不写了。
Python解法如下:
import heapq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return heapq.nlargest(k, nums)[-1]
C++解法如下:
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int,vector<int>,greater<int>> q;
for(int i=0;i<nums.size();i++)
{
if(q.size()<k) q.push(nums[i]);
else if(q.top()<nums[i])
{
q.pop();
q.push(nums[i]);
}
}
return q.top();
}
};