|
| 1 | +""" |
| 2 | + Design a class to find the kth largest element in a stream. Note that it is |
| 3 | + the kth largest element in the sorted order, not the kth distinct element. |
| 4 | +
|
| 5 | + Your KthLargest class will have a constructor which accepts an integer k |
| 6 | + and an integer array nums, which contains initial elements from the stream. |
| 7 | + For each call to the method KthLargest.add, return the element representing |
| 8 | + the kth largest element in the stream. |
| 9 | +
|
| 10 | + Example: |
| 11 | + int k = 3; |
| 12 | + int[] arr = [4,5,8,2]; |
| 13 | + KthLargest kthLargest = new KthLargest(3, arr); |
| 14 | + kthLargest.add(3); // returns 4 |
| 15 | + kthLargest.add(5); // returns 5 |
| 16 | + kthLargest.add(10); // returns 5 |
| 17 | + kthLargest.add(9); // returns 8 |
| 18 | + kthLargest.add(4); // returns 8 |
| 19 | +
|
| 20 | + Note: |
| 21 | + You may assume that nums' length ≥ k-1 and k ≥ 1. |
| 22 | +""" |
| 23 | +#Difficulty: Easy |
| 24 | +#10 / 10 test cases passed. |
| 25 | +#Runtime: 968 ms |
| 26 | +#Memory Usage: 18 MB |
| 27 | + |
| 28 | +#Runtime: 968 ms, faster than 20.55% of Python3 online submissions for Kth Largest Element in a Stream. |
| 29 | +#Memory Usage: 18 MB, less than 16.11% of Python3 online submissions for Kth Largest Element in a |
| 30 | + |
| 31 | +class KthLargest: |
| 32 | + |
| 33 | + def __init__(self, k: int, nums: List[int]): |
| 34 | + self.nums = nums |
| 35 | + self.k = k |
| 36 | + |
| 37 | + def add(self, val: int) -> int: |
| 38 | + self.nums.append(val) |
| 39 | + self.nums.sort() |
| 40 | + return self.nums[-self.k] |
| 41 | + |
| 42 | + |
| 43 | +# Your KthLargest object will be instantiated and called as such: |
| 44 | +# obj = KthLargest(k, nums) |
| 45 | +# param_1 = obj.add(val) |
0 commit comments