File tree 2 files changed +37
-0
lines changed
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ *** 给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。***
2
+
3
+ ```
4
+ import heapq
5
+ import collections
6
+ class Solution(object):
7
+ def topKFrequent(self, nums, k):
8
+ """
9
+ :type nums: List[int]
10
+ :type k: int
11
+ :rtype: List[int]
12
+ """
13
+ count = collections.Counter(nums)
14
+ heap = []
15
+ for key, val in count.items():
16
+ if len(heap) >= k:
17
+ if val > heap[0][0]:
18
+ heapq.heapreplace(heap, (val, key))
19
+ else:
20
+ heapq.heappush(heap, (val, key))
21
+ return [item[1] for item in heap]
22
+ ```
Original file line number Diff line number Diff line change
1
+ *** 输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。***
2
+
3
+ ```
4
+ class Solution:
5
+ def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
6
+ if k == 0:
7
+ return list()
8
+ hp = [-x for x in arr[:k]]
9
+ heapq.heapify(hp)
10
+ for i in range(k, len(arr)):
11
+ if hp[0] < -arr[i]:
12
+ heapq.heapreplace(hp, -arr[i])
13
+ ans = [-x for x in hp]
14
+ return ans
15
+ ```
You can’t perform that action at this time.
0 commit comments