LeetCode 347. Top K Frequent Elements
Description
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.
描述
給定一個非空的整數陣列,返回其中出現頻率前 k 高的元素。
示例 1:
輸入: nums = [1,1,1,2,2,3], k = 2
輸出: [1,2]
示例 2:
輸入: nums = [1], k = 1
輸出: [1]
說明:
你可以假設給定的 k 總是合理的,且 1 ≤ k ≤ 陣列中不相同的元素的個數。
你的演算法的時間複雜度必須優於 O(n log n) , n 是陣列的大小。
思路
- 使用字典,統計每個元素出現的次數,元素為鍵,元素出現的次數為值。
- 然後以元素出現的次數為值,統計該次數下出現的所有的元素。
- 從最大次數遍歷到 1 次,若該次數下有元素出現,提取該次數下的所有元素到結果陣列中,知道提取到 k 個元素為止。
# -*- coding: utf-8 -*- # @Author:何睿 # @Create Date:2019-04-09 12:37:36 # @Last Modified by:何睿 # @Last Modified time: 2019-04-09 15:57:00 from collections import Counter class Solution: def topKFrequent(self, nums: [int], k: int) -> [int]: # 桶 bucket = dict() # 構建字典,鍵位數字,值為該數字出現過的次數 table = Counter(nums) result, count = [], 0 # 以元素出現的次數位鍵,該次數下的所有元素構成的 List 為值 for num, times in table.items(): if times not in bucket: bucket[times] = [] bucket[times].append(num) # 出現的最大次數 maxtime = max(table.values()) for time in range(maxtime, 0, -1): # 如果該次數下有元素 if time in bucket: # 提取當前次數下的所有元素到結果中 result.extend(bucket[time]) count += len(bucket[time]) if count == k: break return result
原始碼檔案在這裡 。
©本文首發於 何睿的部落格 ,歡迎轉載,轉載需保留文章來源 ,作者資訊和本宣告.