0347-leetcode演算法實現之前K個高頻元素-top-k-frequent-elements-python&golang實現
阿新 • • 發佈:2021-11-10
給你一個整數陣列 nums 和一個整數 k ,請你返回其中出現頻率前 k 高的元素。你可以按 任意順序 返回答案。
示例 1:
輸入: nums = [1,1,1,2,2,3], k = 2
輸出: [1,2]
示例 2:
輸入: nums = [1], k = 1
輸出: [1]
提示:
1 <= nums.length <= 105
k 的取值範圍是 [1, 陣列中不相同的元素的個數]
題目資料保證答案唯一,換句話說,陣列中前 k 個高頻元素的集合是唯一的
進階:你所設計演算法的時間複雜度 必須 優於 O(n log n) ,其中 n是陣列大小。
來源:力扣(LeetCode)
連結: https://leetcode-cn.com/problems/top-k-frequent-elements
python
# 0347.前k個高頻元素 # https://leetcode-cn.com/problems/top-k-frequent-elements/solution/dai-ma-sui-xiang-lu-347-qian-kge-gao-pin-efgx/ # 時間複雜度:O(nlogk) # 空間複雜度:O(n) import heapq class Solution2: def topKFrequent(self, nums: List[int], k: int) -> List[int]: # 要統計元素出現頻率 map_ = {} # nums[i]:對應出現的次數 for i in range(len(nums)): map_[nums[i]] = map_.get(nums[i], 0) + 1 # 對頻率排序 # 定義一個小頂堆,大小為k pri_que = [] # 小頂堆 # 用固定大小為k的小頂堆,掃面所有頻率的數值 for key, freq in map_.items(): heapq.heappush(pri_que, (freq, key)) if len(pri_que) > k: # 如果堆的大小大於了K,則佇列彈出,保證堆的大小一直為k heapq.heappop(pri_que) # 找出前K個高頻元素,因為小頂堆先彈出的是最小的,所以倒敘來輸出到陣列 result = [0] * k for i in range(k - 1, -1, -1): result[i] = heapq.heappop(pri_que)[1] return result # https://leetcode-cn.com/problems/top-k-frequent-elements/solution/python-dui-pai-xu-by-xxinjiee/ class Solution: # 小頂堆-力扣超時! def topKFrequent(self, nums: [int], k: int) -> [int]: def sift_down(arr, root, k): """下沉logk, 如果新的根節點>子節點就一直下沉""" val = arr[root] while root << 1 < k: child = root << 1 # 選取左右孩子中小的父節點交換 if child | 1 < k and arr[child[1][1]] < arr[child][1]: child |= 1 # 如果子節點<新節點,交換, 如果有序break if arr[child][1] < val[1]: arr[root] = arr[child] root = child else: break arr[root] = val def sift_up(arr, child): """上浮logk, 如果新加入的節點<父節點就一直上浮""" val = arr[child] while child >> 1 > 0 and val[1] < arr[child>>1][1]: arr[child] = arr[child>>1] child>>1 arr[child] = val from collections import Counter stat = Counter(nums) stat = list(stat.items()) heap = [(0, 0)] # 構建規模為k+1的堆,新元素加入堆尾,上浮 for i in range(k): heap.append(stat[i]) sift_up(heap, len(heap)-1) # 維護規模為k+1的堆,如果新元素大於堆頂,入堆並下沉 for i in range(k, len(stat)): if stat[i][1] > heap[1][1]: heap[1] = stat[i] sift_down(heap, 1, k+1) return [item[0] for item in heap[1:]] # 大頂堆 堆排序 def heapSort(arr): """ 從後往前非葉子節點下沉,依次向上保證每一個子樹都是大頂堆,構造大頂錐 依次把大頂堆根節點與尾部節點交換(不再維護,堆規模 -1),新根節點下沉。 :param arr: :return: """ def sift_down(arr, root, k): val = arr[root] while root << 1 < k: child = root << 1 if child|1 < k and arr[child|1] > arr[child]: child |= 1 if arr[child] > val: arr[root] = arr[child] root = child else: break arr[root] = val arr = [0] + arr k = len(arr) for i in range((k-1)>>1, 0, -1): sift_down(arr, i, k) for i in range(k-1, 0, -1): arr[1], arr[i] = arr[i], arr[1] sift_down(arr, 1, i) return arr[1:]
golang
//方法一:小頂堆 func topKFrequent(nums []int, k int) []int { map_num:=map[int]int{} //記錄每個元素出現的次數 for _,item:=range nums{ map_num[item]++ } h:=&IHeap{} heap.Init(h) //所有元素入堆,堆的長度為k for key,value:=range map_num{ heap.Push(h,[2]int{key,value}) if h.Len()>k{ heap.Pop(h) } } res:=make([]int,k) //按順序返回堆中的元素 for i:=0;i<k;i++{ res[k-i-1]=heap.Pop(h).([2]int)[0] } return res } //構建小頂堆 type IHeap [][2]int func (h IHeap) Len()int { return len(h) } func (h IHeap) Less (i,j int) bool { return h[i][1]<h[j][1] } func (h IHeap) Swap(i,j int) { h[i],h[j]=h[j],h[i] } func (h *IHeap) Push(x interface{}){ *h=append(*h,x.([2]int)) } func (h *IHeap) Pop() interface{}{ old:=*h n:=len(old) x:=old[n-1] *h=old[0:n-1] return x } //方法二:利用O(logn)排序 func topKFrequent(nums []int, k int) []int { ans:=[]int{} map_num:=map[int]int{} for _,item:=range nums { map_num[item]++ } for key,_:=range map_num{ ans=append(ans,key) } //核心思想:排序 //可以不用包函式,自己實現快排 sort.Slice(ans,func (a,b int)bool{ return map_num[ans[a]]>map_num[ans[b]] }) return ans[:k] } 作者:carlsun-2 連結:https://leetcode-cn.com/problems/top-k-frequent-elements/solution/dai-ma-sui-xiang-lu-347-qian-kge-gao-pin-efgx/