ZhangZhihui's Blog  

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

 

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

 

Constraints:

  • 1 <= k <= nums.length <= 105
  • -104 <= nums[i] <= 104

 

My Solution 1:

import heapq


class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        max_heap = []

        for num in nums:
            heapq.heappush(max_heap, -1 * num)

        i = 1
        while i <= k:
            ith_largest = -1 * heapq.heappop(max_heap)
            i += 1
        
        return ith_largest

 

 

My Solution 2:

import heapq


class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        return heapq.nlargest(k, nums)[-1]

 

 

posted on 2025-04-02 21:00  ZhangZhihuiAAA  阅读(13)  评论(0)    收藏  举报