leetcode Top K Frequent Elements

leetcode 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.

题目地址:leetcode Top K Frequent Elements 

题意:

给定一个数组,返回其出现次数最多的k个元素,要求复杂度小于O(nlogn)

思路:

首先扫一遍数组进行计数。

接着用一个长度为k 堆,存储出现次数最多的元素(堆顶的元素最小,每次和堆顶的元素比较即可)

 

C++

 

Python

 

 

本题是leetcode 347 Top K Frequent Elements  题解,

更多题解可以查看:https://www.hrwhisper.me/leetcode-algorithm-solution/

本博客若无特殊说明则由 hrwhisper 原创发布
转载请点名出处:细语呢喃 > leetcode Top K Frequent Elements
本文地址:https://www.hrwhisper.me/leetcode-top-k-frequent-elements/

您的支持将鼓励我继续创作!

Leetcode , , , . permalink.

2 thoughts on “leetcode Top K Frequent Elements

Leave a Reply

Your email address will not be published. Required fields are marked *