Leetcode 703. Kth largest Element in a Stream

Source: Internet
Author: User

The original title link is here: https://leetcode.com/problems/kth-largest-element-in-a-stream/description/

Topic:

Design a class to find the kth largest element in a stream. Note that it was the kth largest element in the sorted order and not the kth distinct element.

Your KthLargest class'll has a constructor which accepts an integer k and an integer array nums , which contains initial Elements from the stream. For each call KthLargest.add to the method, 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 4kthlargest.add (5);  Returns 5kthlargest.add (10);   Returns 5kthlargest.add (9);   Returns 8kthlargest.add (4); Returns 8

Note:
Assume that nums ' length≥ and k-1 k ≥1.

Exercises

Maintain size with minheap in K.

Time Complexity:kthlargest, O (n * logk). Add O (LOGK). n = nums.length.

Space:o (k).

AC Java:

1 classKthlargest {2Priorityqueue<integer>minheap;3     intK;4     5      PublicKthlargest (intKint[] nums) {6          This. Minheap =NewPriorityqueue<integer>();7          This. K =K;8          for(intnum:nums) {9 Add (num);Ten         } One     } A      -      Public intAddintval) { -         if(Minheap.size () <k) { the Minheap.add (val); -}Else if(Minheap.peek () <val) { - Minheap.poll (); - Minheap.add (val); +         } -          +         returnMinheap.peek (); A     } at } -  - /** - * Your Kthlargest object would be instantiated and called as such: - * Kthlargest obj = new Kthlargest (k, nums); - * int param_1 = Obj.add (val); in  */

Leetcode 703. Kth largest Element in a Stream

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.