找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 18|回复: 0

347. Top K Frequent Elements

[复制链接]

12

主题

0

回帖

32

积分

管理员

积分
32
发表于 2025-10-3 11:15:01 | 显示全部楼层 |阅读模式
Q:
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:
Input: nums = [1], k = 1
Output: [1]

Example 3:
Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2
Output: [1,2]


Constraints:
  • 1 <= nums.length <= 105
  • -104 <= nums <= 104
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

A:



#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;

vector<int> topKFrequent(vector<int>& nums, int k) {
    // Step 1: Count the frequency of each element
    unordered_map<int, int> freq_map;
    for (int num : nums) {
        freq_map[num]++;
    }

    // Step 2: Use a min-heap to keep the k most frequent elements
    // Priority queue stores pairs: (-frequency, element), we negate the frequency
    // to simulate a max-heap using a min-heap.
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_heap;

    for (const auto& entry : freq_map) {
        min_heap.push({entry.second, entry.first});
        // If heap size exceeds k, pop the least frequent element
        if (min_heap.size() > k) {
            min_heap.pop();
        }
    }

    // Step 3: Extract the top k elements from the heap
    vector<int> result;
    while (!min_heap.empty()) {
        result.push_back(min_heap.top().second);
        min_heap.pop();
    }

    return result;
}





您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|茶之知社区

GMT+8, 2025-12-28 20:55 , Processed in 0.065565 second(s), 22 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表