Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Top K Frequent Elements

Posted on January 26, 2018July 26, 2020 by braindenny

Top K Frequent Elements



Similar Problems:

  • LeetCode: Find K Pairs with Smallest Sums
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #heap, topk

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note:
You may assume k is always valid, 1 <= k <= number of unique elements.
Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/top-k-frequent-elements
// Basic Ideas: heap
//
// Complexity: Time O(n*log(k)), Space O(n)
import "container/heap"

type MyNode struct {
    val int
    cnt int
}

// min heap
type IntHeap []MyNode
func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i].cnt < h[j].cnt }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
        // Push and Pop use pointer receivers because they modify the slice's length,
        // not just its contents.
        *h = append(*h, x.(MyNode))
}

func (h *IntHeap) Pop() interface{} {
        res := (*h)[len(*h)-1]
        *h = (*h)[0:len(*h)-1]
        return res
}

func topKFrequent(nums []int, k int) []int {
    m := map[int]int{}
    for _, num := range nums{ m[num]++ }
    h := &IntHeap{}
    heap.Init(h)
    for key, val := range m {
        heap.Push(h, MyNode{val:key, cnt:val})
        if h.Len() > k { heap.Pop(h) }
    }
    res := make([]int, k)
    i:=k-1
    for h.Len() != 0 {
        item := heap.Pop(h).(MyNode)
        res[i] = item.val
        i--
    }
    return res
}
## https://code.dennyzhang.com/top-k-frequent-elements
## Basic Ideas: priority queue: heapq
##
## Complexity:
import collections, heapq
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        q = []
        heapq._heapify_max(q)
        m = collections.defaultdict(lambda: 0)
        for num in nums: m[num] += 1
        # python heapq doesn't support max heap by default
        for num in m: heapq.heappush(q, (-m[num], num))

        res = []
        for i in xrange(k):
            (count, num) = heapq.heappop(q)
            res.append(num)
        return res
linkedin
github
slack

Post Views: 8
Posted in BasicTagged #heap, #topk

Post navigation

LeetCode: Top K Frequent Words
LeetCode: Sort Characters By Frequency

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.