HTMLify

LeetCode - Kth Largest Element in a Stream - Python
Views: 12 | Author: abh
class KthLargest:

    def __init__(self, k: int, nums: List[int]):
        self.values = sorted(nums)
        self.k = k

    def add(self, val: int) -> int:
        if not self.values:
            self.values.append(val)
            return val
        
        for i, v in enumerate(self.values):
            if val < v:
                self.values.insert(i, val)
                break
        else:
            self.values.append(val)
        
        if len(self.values) <= self.k:
            return self.values[0]
        
        return self.values[-self.k]


# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)

Comments