LeetCode : Kth Largest Element in a Stream
Published in
1 min readSep 21, 2019
My submission is below.
import bisectclass KthLargest(object):def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.k = k
self.nums = sorted(nums)[-k:]def add(self, val):
"""
:type val: int
:rtype: int
"""
k = self.k
bisect.insort(self.nums,val)
if len(self.nums) > k:
self.nums = self.nums[-k:]
return self.nums[0]
This solution is slow.
Faster solutions than mine are often written with heapq
.