zoukankan      html  css  js  c++  java
  • LeetCode 703. Kth Largest Element in a Stream

    原题链接在这里:https://leetcode.com/problems/kth-largest-element-in-a-stream/description/

    题目:

    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.

    Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

    Example:

    int k = 3;
    int[] arr = [4,5,8,2];
    KthLargest kthLargest = new KthLargest(3, arr);
    kthLargest.add(3);   // returns 4
    kthLargest.add(5);   // returns 5
    kthLargest.add(10);  // returns 5
    kthLargest.add(9);   // returns 8
    kthLargest.add(4);   // returns 8
    

    Note: 
    You may assume that nums' length ≥ k-1 and k ≥ 1.

    题解:

    用minHeap维持size在k. 

    Time Complexity: KthLargest, O(n * logk). add O(logk). n = nums.length. 

    Space: O(k).

    AC Java:

     1 class KthLargest {
     2     PriorityQueue<Integer> minHeap;
     3     int k;
     4     
     5     public KthLargest(int k, int[] nums) {
     6         this.minHeap = new PriorityQueue<Integer>();
     7         this.k = k;
     8         for(int num : nums){
     9             add(num);
    10         }
    11     }
    12     
    13     public int add(int val) {
    14         if(minHeap.size() < k){
    15             minHeap.add(val);
    16         }else if(minHeap.peek() < val){
    17             minHeap.poll();
    18             minHeap.add(val);
    19         }
    20         
    21         return minHeap.peek();
    22     }
    23 }
    24 
    25 /**
    26  * Your KthLargest object will be instantiated and called as such:
    27  * KthLargest obj = new KthLargest(k, nums);
    28  * int param_1 = obj.add(val);
    29  */
  • 相关阅读:
    JSP页面间传递参数
    JSP获取当前日期时间
    jsp实现套打(发票打印)
    iframe
    HTTP状态码及含义大全
    标签 -- HTML内联框架
    jstl fmt标签详解
    button和submit的区别及使用js实现页面跳转的方式
    Idea SpringBoot 启动Eurka 报错,提示端口被占用
    CodeSmith 破解
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/9785044.html
Copyright © 2011-2022 走看看