# 【Leetcode】215. 数组中的第K个最大元素

## 方法一：

class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
#这个题目显然可以使用heap来完成
sort_list=sorted(nums)
return sort_list[-k]

不会吧不会吧！竟然打败了97%的用户？？？据我所知，python的sorted函数其实使用了快速排序，那么时间复杂度是O（nlogn）,那我们用时间复杂度更小的heap sort来试试看？

## 方法二：

class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = []
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]

## 方法三：

class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = Heap(k + 1)
for num in nums:
if not heap.push(num):
heap.pop()
heap.push(num)
if heap.size == k + 1:
heap.pop()
return heap.peek()

class Heap:
def __init__(self, length):
self.heap = [0] * (length + 1)
self.size = 0

def push(self, val):
if self.size == len(self.heap) - 1:
return False
self.size += 1
self.heap[self.size] = val
self.shift_up(self.size)
return True

def pop(self):
val = self.heap[1]
self.heap[1] = self.heap[self.size]
self.heap[self.size] = 0
self.size -= 1
self.shift_down(1)
return val

def peek(self):
return self.heap[1]

def shift_up(self, i):
val = self.heap[i]
while i >> 1 > 0:
parent = i >> 1
if val < self.heap[parent]:
self.heap[i] = self.heap[parent]
i = parent
else:
break
self.heap[i] = val

def shift_down(self, i):
val = self.heap[i]
while i << 1 <= self.size:
child = i << 1
if child != self.size and self.heap[child + 1] < self.heap[child]:
child += 1
if val > self.heap[child]:
self.heap[i] = self.heap[child]
i = child
else:
break
self.heap[i] = val

posted @ 2021-04-20 16:59  Geeksongs  阅读(87)  评论(2编辑  收藏  举报