[LeetCode] 703. Kth Largest Element in a Stream, Easy

2025. 4. 11. 15:58·CodingTest/LeetCode
반응형

1. 문제

  • 정수 배열과 k가 주어질 때, add 후 k 번째로 큰 숫자를 반환하는 클래스를 작성하라.

2. 해결

class TreeCountNode {
    cnt: number;
    val: number;
    left: TreeCountNode | null;
    right: TreeCountNode | null;
    constructor(val:number, left?: TreeCountNode | null, right?: TreeCountNode | null) {
        this.cnt = 1;
        this.val = val;
        this.left = left || null;
        this.right = right || null;
    }
}

class KthLargest {
    k: number;
    root: TreeCountNode | null;
    constructor(k: number, nums: number[]) {
        this.k = k;
        
        for(const num of nums) {
            this.root = this.insert(this.root, num)     
        }
    }

    insert(node: TreeCountNode | null, value: number):TreeCountNode | null {
        if(!node) return new TreeCountNode(value);
        
        node.cnt++;

        if (value < node.val) {
            node.left = this.insert(node.left, value);
        } else {
            node.right = this.insert(node.right, value);
        }


        return node;
    }

    add(val: number): number {
        this.root = this.insert(this.root, val);
        return this.findKth(this.root, this.k);
    }

    findKth(node: TreeCountNode | null, k:number):number {
        if(!node) return -1;

        const rightCount = node.right ? node.right.cnt : 0;

        if(k <= rightCount) {
            return this.findKth(node.right, k);
        } else if(k === rightCount + 1) {
            return node.val;
        } else {
            return this.findKth(node.left, k - rightCount -1);
        }

    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */
  • 노드에 cnt라는 필드를 통해 서브 트리에 존재하는 노드의 수를 저장.
  • 입력받은 배열로 BST를 구성, 오른쪽 -> 자신 -> 왼쪽 순으로 탐색하면서 큰 수를 찾는다.
  • 못풀었다. 다른 풀이 참고.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 110. Balanced Binary Tree, Easy
  • [LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree, Medium
  • [LeetCode] 450. Delete Node in a BST, Medium
  • [LeetCode] 701. Insert into a Binary Search Tree, Medium
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    boj1427
    백준1427
    boj2108
    백준2751
    백준7576자바
    Easy
    TypeScript
    프로그래머스
    Java
    next 14
    알고리즘
    meidum
    백준7576
    백준1260
    component-scan
    BOJ
    백준
    medium
    leetcode 2236
    자바
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 703. Kth Largest Element in a Stream, Easy
상단으로

티스토리툴바