赞
踩
题目:
给定一个数组,求出该数组中出现次数最多的前K个元素内容。要求复杂度为 nlog(n) .
解题思路:
使用哈希表(python 中字典)来存储各个元素出现的次数,键(key)为对应元素,值(value)为对应元素出现个数。再对该哈希表(字典)按照值进行排序。
代码(Python):
- class Solution(object):
- def topKFrequent(self, nums, k):
- """
- :type nums: List[int]
- :type k: int
- :rtype: List[int]
- """
- Dict = {}
- for i in range(len(nums)):
- if nums[i] in Dict:
- Dict[nums[i]] = Dict[nums[i]] + 1
- else:
- Dict[nums[i]] = 1
-
- output = sorted(Dict.items(),key=lambda e:e[1],reverse=True)
-
- final = []
- for i in range(k):
- final.append(output[i][0])
- return final

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。