From 3362183d8446e551f0361ead95dca6bec8b7411a Mon Sep 17 00:00:00 2001 From: boom-jumper <56831966+boom-jumper@users.noreply.github.com> Date: Tue, 1 Jun 2021 18:08:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00347=E5=89=8DK=E4=B8=AA?= =?UTF-8?q?=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0=20python3=20=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 57 ++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 841584b4..29963b48 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -162,6 +162,63 @@ class Solution { Python: +```python +class Solution: + def sift(self, alist, low, high): + '''小根堆构建''' + i = low + j = 2 * i + 1 + tmp = alist[low] + while j <= high: + if j + 1 <= high and alist[j+1] <= alist[j]: + j += 1 + if alist[j] < tmp: + alist[i] = alist[j] + i = j + j = 2 * i + 1 + else: + alist[i] = tmp + break + else: + alist[i] = tmp + + + def topK(self, nums, k): + # 建立小根堆 + heap = nums[:k] + for i in range((k-2)//2, -1, -1): + self.sift(heap, i, k-1) + + # 把后续的k到len(nums)填充到小根堆里 + for i in range(k, len(nums)): + if nums[i] >= heap[0]: + heap[0] = nums[i] + self.sift(heap, 0, k-1) + + # 排序 + for i in range(k-1, -1, -1): + heap[0], heap[i]= heap[i], heap[0] + self.sift(heap, 0, i-1) + return heap + + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + dict1 = dict() + for val in nums: + if val not in dict1: + dict1[val] = 1 + else: + dict1[val] += 1 + res = list() + ind = list() + for item in dict1: + res.append([dict1[item], item]) + result = list() + heap = self.topK(res, k) + print(heap) + for val in heap: + result.append(val[1]) + return result +``` Go: