반응형
    
    
    
  https://leetcode.com/problems/kth-largest-element-in-a-stream/description/
Kth Largest Element in a Stream - LeetCode
Can you solve this real interview question? Kth Largest Element in a Stream - Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class:
leetcode.com
📕 풀이방법
📔 입력 및 초기화
큰 원소를 pq top으로 우선순위를 가지는 queue pq와 k를 선언 후 class 생성자에서 nums의 원소를 받아 값을 저장해줍니다.
📔 풀이과정
pq의 top은 항상 k번째로 큰 수가 저장되도록 add함수에서 val을 push후 pq.size() > k인 동안 원소에서 pop해줍니다.
📔 정답 출력 | 반환
pq의 top을 반환합니다.
📕 Code
📔 C++
class KthLargest {
public:
    int k;
    priority_queue <int, vector<int>, greater<int>> pq;
    
    KthLargest(int k, vector<int>& nums) {
        this->k = k;
        for(auto n : nums) pq.push(n);
    }
    
    int add(int val) {
        pq.push(val);
        while(pq.size() > k) {
            pq.pop();
        }
        return pq.top();
    }
};
/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > 자료구조' 카테고리의 다른 글
| (C++) - LeetCode (easy) 771. Jewels and Stones (0) | 2023.07.12 | 
|---|---|
| (C++) - LeetCode (easy) 706. Design HashMap (0) | 2023.06.20 | 
| (C++) - LeetCode (easy) 697. Degree of an Array (0) | 2023.06.14 | 
| (C++) - LeetCode (easy) 671. Second Minimum Node In a Binary Tree (0) | 2023.06.07 | 
| (C++) - LeetCode (easy) 705. Design HashSet (0) | 2023.05.30 |