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();
}
};