347.Top-K-Frequent-Elements

347. Top K Frequent Elements

题目地址

https://leetcode.com/problems/top-k-frequent-elements/

题目描述

Given a non-empty array of integers, return the k most frequent elements.

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

Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:

You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

代码

Approach 1: Heap

Complexity Analysis

  • Time complexity : O(N_log(_k)). The complexity of `Counter method is O(N). To build a heap and output list takes O(N_log(_k)). Hence the overall complexity of the algorithm is O(N+N_log(_k)=O(N_log(_k).

  • Space complexity : O(N) to store the hash map.

Last updated

Was this helpful?