# Leetcode:703题——数据流中的第k大元素

class KthLargest:

def __init__(self, k: int, nums: List[int]):
#建堆,构造小根堆
self.nums = nums
self.length = len(nums)
self.k = k
m = self.length
#把序列的逻辑结构看做一颗完全二叉树
'''i为当前节点，2*i+1是i的左孩子，2*i+2是i的右孩子'''
r = m // 2 - 1    #从最后一个叶节点的父节点开始
while r >= 0:
self.heapsort(r,m)
r -= 1
while m-1 > self.k-1:
'''把self.length-k个值，即刚开始的堆的前面的几个最小值调换到末尾，'''
temp = self.nums[0]
self.nums[0] = self.nums[m-1]
self.nums[m-1] = temp
m = m-1
self.heapsort(0,m)
def add(self, val: int) -> int:
#插入val
if not self.nums:
self.nums.append(val)
elif self.k > len(self.nums):
self.nums.append(val)
self.heapsort(0,self.k)
elif val > self.nums[0]:
self.nums[0] = val
self.heapsort(0,self.k)
return self.nums[0]
def heapsort(self,r,m):
'''小根堆的排序'''
temp = self.nums[r]
j = 2*r + 1
while j < m:
if j+1 < m and self.nums[j] > self.nums[j+1]:
j += 1     #往右孩子走
if j < m and temp <= self.nums[j]:
break
self.nums[r] = self.nums[j]
r = j
j = 2*j+1
self.nums[r] = temp



09-01 141

08-05 74

02-14 17

04-10 79

11-04 36

01-25 69

05-26 225

10-26 11

08-28 29

10-20 15

07-23 870

03-31 62

08-29 80

02-14 308

02-23 71

10-24 125

10-21 147

05-05 49

04-14 59万+

03-13 15万+

03-04 13万+

03-05 6317

03-08 5万+

03-08 7万+

03-10 13万+

03-12 11万+

03-13 11万+

03-14 1万+

03-18 5818

03-18 9757

03-19 3万+

03-19 8万+

03-20 8877

03-24 3万+

03-25 3万+

05-08 5万+

03-25 9万+

03-29 21万+

03-29 1万+

03-29 10万+

03-30 16万+

05-28 6091

05-28 1万+

04-02 4万+

04-03 3446

04-06 7万+

04-07 5万+

04-09 8万+

04-09 2万+

05-17 8435

04-10 2841

04-11 3万+

04-15 6万+

04-18 4万+

04-20 4万+

04-24 3万+

04-29 6248

04-29 7020

04-30 4899

04-30 9950

04-30 9518

05-16 5万+

05-08 4万+

05-11 3万+

05-12 1万+

05-13 708

05-14 6425

05-14 1945

05-16 1万+

05-20 956

05-18 8360

05-27 1356

05-18 3544

05-19 1万+

05-21 7328

05-21 7370

05-25 5271

05-22 359

05-23 1万+

#### 63个Linux基础自测题,超过10个不会的,劝你还是别玩Linux了

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客