Tag: Array、Heap、Divide and Conquer
Difficulty: Medium
Description:
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.
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
Key Word: QuickSelect
Code:
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {integer}
def findKthLargest(self, nums, k):
pivot = nums[0]
nums1, nums2 = [], []
for num in nums:
if num > pivot:
nums1.append(num)
elif num < pivot:
nums2.append(num)
if k <= len(nums1):
return self.findKthLargest(nums1, k)
if k > len(nums) - len(nums2):
return self.findKthLargest(nums2, k - (len(nums) - len(nums2)))
return pivot

本文介绍了一种在未排序数组中查找第K大元素的方法,使用快速选择算法实现。通过不断划分数组,直到找到目标元素的位置。这种方法适用于编程竞赛及实际问题解决。
839

被折叠的 条评论
为什么被折叠?



