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.
LeetCode:链接
题目的意思是让找到第K大的数。
第一种方法:partition思想。正常的快排是从小到大,当选定一个base的时候让左边的元素都比它小,右边的元素都比它大。但是现在因为是要求第K个最大的数,所以要反过来,从大到小排序,当选定一个base的时候让左边的元素都比它大,右边的元素都比它小。举个例子,数组[3,2,1,5,4,6],假设每次选最左边的元素作为主元素,那么我们在一次排序后,数组变为[5,6,4,3,1,2]。现在3变成了第四大的元素。
class Solution(object):
def partition(self, nums, start, end):
if end <= start:
return start
base = nums[start]
while start < end:
while start < end and nums[end] <= base:
end -= 1
nums[start] = nums[end]
while start < end and nums[start] >= base:
start += 1
nums[end] = nums[start]
nums[start] = base
return start
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums or k > len(nums) or k <= 0:
return None
length = len(nums)
index = self.partition(nums, 0, length-1)
while index != k-1:
if index > k-1:
index = self.partition(nums, 0, index-1)
elif index < k-1:
index = self.partition(nums, index+1, length-1)
return nums[k-1]
第二种方法:堆排序。建立一个最小堆,接下来用数组中的数去和堆顶比较。如果比堆顶小,则不处理;如果比堆顶大,则替换堆顶,然后依次下沉到适当的位置。时间复杂度是O(NlogK)。因为题目要求的是找到第K大的数,所以直接输出最小堆的堆顶即可。只调整不经过堆排序得到的堆都是无序的!!
class Solution(object):
def HeadAdjust(self, input_list, parent, length):
temp = input_list[parent]
child = 2 * parent + 1
while child < length:
if child + 1 < length and input_list[child+1] < input_list[child]:
child += 1
if temp <= input_list[child]:
break
input_list[parent] = input_list[child]
parent = child
child = 2 * parent + 1
input_list[parent] = temp
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums or k > len(nums) or k <= 0:
return None
input_list = nums[:k]
for i in range(k//2)[::-1]:
self.HeadAdjust(input_list, i, k)
for j in nums[k:]:
cur_min = input_list[0]
if j > cur_min:
input_list[0] = j
self.HeadAdjust(input_list, 0, k)
return input_list[0]