[Leetcode] Heap, Divide and conquer--215. Kth Largest Element in an Array

本文介绍了在未排序数组中寻找第K大元素的四种不同方法:快速排序、快速选择、堆以及多集。每种方法都附带了详细的解释及Python实现代码,并对比了它们的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

Solution:

 1st method using quicksort to sort in non-ascending order, and get the kth number. n = len(nums), time complexity is o(nlogn) -

 

 2nd method. quickselect. set the pivot (e.g. the first element ) and rearrange all the element less than pivot to be in the left, bigger than pivot to be in the right; then compare with the pivot index with k to decide to go next in the left part or right part to recursively do the same thing reference introduction to algorithm texbook or --reference https://en.wikipedia.org/wiki/Selection_algorithm https://discuss.leetcode.com/topic/14611/java-quick-select/2 random algorithm ; Amortized time complexity is o(n), worst case is o(n^2)

 1  def select(nums, l, r, index):
 2             if r == l:
 3                 return nums[l]
 4             #pivot index
 5             pind = random.randint(l, r)
 6             nums[l], nums[pind] = nums[pind], nums[l]   #move pivot to the beginning of the
 7             
 8             #partition around pivot
 9             i = l
10             for j in xrange(l+1, r+1):
11                 if nums[j] < nums[l]:
12                     i += 1
13                     nums[i], nums[j] = nums[j], nums[i]
14             nums[i], nums[l] = nums[l],nums[i] 
15             
16             if index == i:
17                 return nums[i]
18             elif index < i:
19                 return select(nums, l, i-1, index)
20             else:
21                 return select(nums, i+1, r, index)
22             
23         index = len(nums) - k
24         if nums is None or len(nums) < 1:
25             return 0
26         return select(nums, 0, len(nums)-1, index)

 

 3rd method, use heap if built-in heapq is allowed in python,

1 h = []
2         for n in nums:
3             heapq.heappush(h, -1*n)     #min-heap
4             
5         for i in range(0, k-1):
6             heapq.heappop(h)
7             
8         return -1*heapq.heappop(h)

 

4th - another method that I have not come up with, which is to use multiset, similar to heap ( it is interesting). --reference https://www.liuchuo.net/archives/3016.

转载于:https://www.cnblogs.com/anxin6699/p/7048263.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值