작심삼일

[LeetCode] 703 | Kth Largests Element in a Stream | Python 본문

스터디/코테

[LeetCode] 703 | Kth Largests Element in a Stream | Python

yun_s 2022. 4. 8. 10:38
728x90
반응형

문제 링크: https://leetcode.com/problems/kth-largest-element-in-a-stream/


문제

Design a class to find the $k^{th}$ largest element in a stream. Note that it is the $k^{th}$ largest element in the sorted order, not the $k^{th}$ distinct element.

Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Appends the integer val to the stream and returns the element representing the $k^{th}$ largest element in the stream.

조건

  • 1 <= k <= $10^4$
  • 0 <= nums.length <= $10^4$
  • $-10^4$ <= nums[i] <= $10^4$
  • $-10^4$ <= val <= $10^4$
  • At most $10^4$ calls will be made to add.
  • It is guaranteed that there will be at least k elements in the array when you search for the $k^{th}$ element.

내 풀이

주어진 nums 리스트를 내림차순으로 정렬한 후 k번째까지만 새로운 리스트(self.kth)에 저장한다.

하나씩 추가될 때마다 self.kth에 추가한 후 똑같이 내림차순으로 정렬해, k번째까지만 저장한 후 k번째 원소를 리턴한다.


코드

class KthLargest:
    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.kth = sorted(nums, reverse=True)[:k]

    def add(self, val: int) -> int:
        self.kth.append(val)
        self.kth = sorted(self.kth, reverse=True)[:self.k]
        return self.kth[-1]


# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
728x90
반응형
Comments