2023-11-29|閱讀時間 ‧ 約 3 分鐘

[Leetcode] 347. Top K Frequent Elements

詳細題目 : 347. Top K Frequent Elements Medium

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.


Example 1:

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

Example 2:

Input: nums = [1], k = 1
Output: [1]



count : { 數字:出現的次數 }

freq : [[],[],[],[]....[]]

list中第i個位置 : 出現的次數

list中第i個位置的內容 : 數字

res : result答案

line 6-7 : 將所有的數字現幾次做分類 { 數字:出現的次數 }

line 8-9 : 將讀取到的次數(count)當作index,將數字(num) append()到第count個陣列中

line 12 : 從freq的後面依序查看

line 13 : 將freq[i]陣列中的數字一直append()直到res的個數等於k


class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = {}
freq = [[] for i in range(len(nums)+1)]

for num in nums:
count[num] = count.get(num, 0) + 1
for num, count in count.items():
freq[count].append(num)

res = []
for i in range(len(freq) - 1, 0, -1):
for n in freq[i]:
res.append(n)
if len(res) == k:
return res





分享至
成為作者繼續創作的動力吧!
這裡會放一些我寫過的 Leetcode 解題,目前的筆記都是使用python做解題
© 2024 vocus All rights reserved.