avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home Leetcode-347-Top K Frequent Elements
文章

Leetcode-347-Top K Frequent Elements

Posted 2022-07-17
4~5 min read

Top K Frequent Elements

leetcode: https://leetcode.com/problems/top-k-frequent-elements/

Description:

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Idea:

**solution **

**Step1: **First use hashmap to record each element and their corresponding frequency.

Step2: create the priority queue and use comparator to build the ascending queue.(the Max heap), so the first element of the queue is the biggest.

Step3: add all element’s and corrsponding frequency to the queue.

Step4: get kth elements of the queue from the first element.

Code:

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        int[] result = new int[k];
        Map<Integer, Integer> map = new HashMap<>();
        //use map to record the element and corresponding frequence
        for(int i=0; i<nums.length; i++){
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }else{
                map.put(nums[i],1);
            }
        }
        //max heap
        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> b[1] - a[1]);
        //store elements to queue
        for (int key : map.keySet())
            queue.add(new int[]{key, map.get(key)});

        //Take the largest k elements in the heap
        int index=0;
        //because the queue is ascending order, so just poll kth elements.
        while(k-->0){
            result[index++] = queue.poll()[0];
        }   
        return result;
    }
}
Leetcode
Leetcode Stack and Queue
Share

Further Reading

Apr 23, 2025

283 - Move Zero

[283 - Move Zero] 🔗 LeetCode Link Problem Description Given an integer array nums, move all 0's to the end of it while maintaining the relative order

Apr 23, 2025

27 - Remove Element

[27 - Remove Element] 🔗 LeetCode Link Problem Description Given an integer array nums and an integer val, remove all occurrences of val in nums in-pl

Apr 23, 2025

26 - Remove Duplicates from Sorted Array

[26 - Remove Duplicates from Sorted Array] 🔗 LeetCode Link Problem Description Given an integer array nums sorted in non-decreasing order, remove the

OLDER

Leetcode-239-Sliding Window Maximum

NEWER

Leetcode-144-Binary Tree Preorder Traversal

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Here’s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents