347. Top K Frequent Elements

Top K Frequent Elements

原题介绍

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

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

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.
Subscribe to see which companies asked this question

给出一个非空整数列表,返回出现频次最大的k个元素

解题思路

O(n)

  1. hash,得到<元素,频次>键值对
  2. 因为频次小于n,建散列表,即新建大小为n+1的数组,数组下标为频次,数组内容为有相同频次的键值list,对散列表按下标由大到小遍历,找出k个键值

ref:https://leetcode.com/discuss/100581/java-o-n-solution-bucket-sort

O(n*log(n-k))

  1. hash map
  2. 新建大小为n-k的最大堆,遍历<元素, 频次>,频次大于堆顶的保存到返回列表,频次小于堆顶的入堆,最后最小堆保存的是出现频次最低的n-k个,被“舍弃”的元素则是出现频次最大的k个

ref:https://leetcode.com/discuss/100562/o-log-k-unordered_map-and-priority_queue-maxheap-solution

你可能感兴趣的:(347. Top K Frequent Elements)