在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
思路:创建一个大顶堆,然后对其进行遍历,找到第k个最大的元素。
执行用时:8 ms, 在所有 Java 提交中击败了36.55%的用户
内存消耗:38.8 MB, 在所有 Java 提交中击败了47.10%的用户
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer>maxheap=new PriorityQueue<>(Collections.reverseOrder());
for(int i=0;i<nums.length;i++)
{
maxheap.add(nums[i]);
}
int res=0;
for(int i=0;i<k;i++)
{
res=maxheap.poll();
}
return res;
}
}
Python:
执行用时:56 ms, 在所有 Python3 提交中击败了51.90%的用户
内存消耗:15.4 MB, 在所有 Python3 提交中击败了35.35%的用户
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
maxheap=[]
heapq.heapify(maxheap)
for i in range(0,len(nums)):
heapq.heappush(maxheap,nums[i]*-1)
res=0
for i in range(0,k):
res=-heapq.heappop(maxheap)
return res