gary@interview:~/interview/coding/347-top-k-freque….md$
$ cat ./coding/347-top-k-frequent-elements.md
[Coding]

347. Top K Frequent Elements

────────────────────────────────────────────────────────────

347. Top K Frequent Elements

將頻率透過

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:

        counter = Counter(nums)

        pq = []

        heapq.heapify(pq)

        for key in counter.keys():
            heapq.heappush(pq, (-counter[key], key))

        res = []

        while k > 0:
            value, key = heapq.heappop(pq)
            res.append(key)
            k -= 1

        return res

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:        
        counter = Counter(nums)
        
        vals = list(counter.values())
        
        heap = []
        for val in vals:
            heapq.heappush(heap, val)
            if len(heap) > k:
                heapq.heappop(heap)
    
        kFreq = heap[0]
    
        res = []
        for key, val in counter.items():
            if val >= kFreq:
                res.append(key)
        
        return res
--tags#Heap
$ ls ./coding/ | grep -v 347-top-k-frequent-elements
265. Paint House II256. Paint House143. Reorder List1762. Buildings With an Ocean View
← cd ../codingcd ~