[Leetcode] 347. Top K Frequent Elements

閱讀時間約 2 分鐘

詳細題目 : 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





7會員
47內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!
Youna's Devlog 的其他內容
[Leetcode] 242. Valid Anagram
閱讀時間約 3 分鐘
[Leetcode] 217. Contains Duplicate
閱讀時間約 2 分鐘
[Leetcode] 1. Two Sum
閱讀時間約 1 分鐘
[Leetcode] 49. Group Anagrams
閱讀時間約 3 分鐘
[Leetcode] 125. Valid Palindrome
閱讀時間約 3 分鐘
[Leetcode] 20. Valid Parentheses
閱讀時間約 3 分鐘
你可能也想看
【LeetCode】19.Remove Nth Node From End of ListInput: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Thumbnail
avatar
2021-10-09
【LeetCode】876. Middle of the Linked ListInput: head = [1,2,3,4,5] Output: [3,4,5] 單看列表只是要找中間值,不過給定的資料結構不是陣列,而是鏈結串列。
Thumbnail
avatar
2021-10-09
【LeetCode】189. Rotate Array之前跳過的題目,回來補完成。 Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]
Thumbnail
avatar
2021-10-08
【LeetCode】557. Reverse Words in a String III今日題目: 把一行字內每個單字都反轉字元。 Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Thumbnail
avatar
2021-10-08
【LeetCode】344. Reverse String今日題目:字串反轉 Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Thumbnail
avatar
2021-10-08
【LeetCode】167. Two Sum II 題目如下: Input: numbers = [2,7,11,15], target = 9 Output: [1,2]
Thumbnail
avatar
2021-10-07
【LeetCode】283. Move Zeroes題目要求如下: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] 把0都搬到後面去,非0的數字移到前面,且不更改原本數字的大小順序。
Thumbnail
avatar
2021-10-07
【LeetCode】977. Squares of a Sorted Array比今天的題目示例如下: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] 簡單來說,要的輸出結果是把陣列內每個數字取平方後,對陣列做排序。
Thumbnail
avatar
2021-10-06
【LeetCode】704. Binary SearchLeetcode上正好有14天的讀書計畫,今天三題都是二分搜索,順手三題都寫一寫,想法上很固定。
Thumbnail
avatar
2021-10-05
【LeetCode】20. Valid Parentheses 前幾天看別人直播刷題,心血來潮打開很久沒動的leetcode試試,挑了一題當初面試沒寫出來的題目。嗯...我那時才剛碰資料結構,知道要用stack寫卻沒實作過任何東西,現在有工作經驗後再來寫,看看會不會有不一樣的想法。
Thumbnail
avatar
2021-10-04