0%

LeetCode 347 - Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

example

1
2
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
1
2
Input: nums = [1], k = 1
Output: [1]

How can we solve this problem?

這一題需要我們返回K個數量最多的element。所以,我們可以使用map記錄我們array中element的個數,然後在把他們以<frequency,element>存到priority queue/max queue,最後只要返回priority queue中的k個element即可。

LeetCode 703 - 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:

  • 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 kth largest element in the stream.

example: