Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

347. Top K Frequent Elements

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:

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

Example 2:

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

找list中個數k的數值,可以用python Counter.most_common,裡面是heapq.nlargest,所以時間複雜度是nlogn,找出符合各數的數字放進ret回傳。

1
2
3
4
5
6
7
8
9
10
11
12
T:O(nlogn), S:O(n)
from collections import Counter
class Solution(object):
def topKFrequent(self, nums, k):
if k == len(nums):return nums
count = Counter(nums).most_common(k) # (數字, 個數)
ret = []
for x,y in count:
ret.append(x)
return ret
或直接
return [x for x, y in collections.Counter(nums).most_common(k)]

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels