347. 前 K 个高频元素 (优先队列 c++)

347. 前 K 个高频元素

难度中等

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

 

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

输入: nums = [1], k = 1
输出: [1]
 
 
from collections import defaultdict
import heapq
class Solution:
    def topKFrequent(self,nums, k):
        #time O(Nlogk)
        #sapce o(n)
        count = defaultdict(int)
        for num in nums:
            count[num] += 1

        heap = []
        for key, val in count.items():
            if len(heap) < k:
                heapq.heappush(heap, (val, key))
            else:
                if val > heap[0][0]:
                    heapq.heappop(heap)
                    heapq.heappush(heap, (val, key))

        return [key for val, key in heap]

 

 

 

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        def sift_down(arr, root, k):
            """下沉log(k),如果新的根节点>子节点就一直下沉"""
            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):
            """上浮log(k),如果新加入的节点<父节点就一直上浮"""
            val = arr[child]
            while child>>1 > 0 and val[1] < arr[child>>1][1]:
                arr[child] = arr[child>>1]
                child >>= 1
            arr[child] = val

        stat = collections.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:]]

 

 

 

 

import heapq
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dd = dict()
        for num in nums:
            if num in dd:
                dd[num]+=1
            else:
                dd[num] = 1
        q = []
        for key in dd.keys():
            q.append((-dd[key],key))
        heapq.heapify(q)
        res = []
        for i in range(k):
            res.append(heapq.heappop(q)[1])
        return res

 

 

【C++】优先队列的预备知识 对于我这种初学者来说,一个优先队列就给我搞蒙了,在此记录一下,造福后来人

## 定义

priority_queue<Type, Container, Functional>;

Type是要存放的数据类型

Container是实现底层堆的容器,必须是数组实现的容器,如vector、deque

Functional是比较方式/比较函数/优先级

priority_queue<Type>;

此时默认的容器是vector,默认的比较方式是大顶堆less<type>

*举例*

//小顶堆
priority_queue <int,vector<int>,greater<int> > q;
//大顶堆
priority_queue <int,vector<int>,less<int> >q;
//默认大顶堆
priority_queue<int> a;
//pair
priority_queue<pair<int, int> > a;
pair<int, int> b(1, 2);
pair<int, int> c(1, 3);
pair<int, int> d(2, 5);
a.push(d);
a.push(c);
a.push(b);
while (!a.empty()) 
{
   cout << a.top().first << ' ' << a.top().second << '\n';
   a.pop();
}
//输出结果为:
2 5
1 3
1 2

## 常用函数

top()

pop()

push()

emplace()

empty()

size()

## 自定义比较方式

当数据类型并不是基本数据类型,而是自定义的数据类型时,就不能用greater或less的比较方式了,而是需要自定义比较方式

在此假设数据类型是自定义的水果:

struct fruit
{
	string name;
	int price;
};

有两种自定义比较方式的方法,如下

### 1.重载运算符

重载”<”

  • 若希望水果价格高为优先级高,则

    //大顶堆
    struct fruit
    {
    	string name;
    	int price;
    	friend bool operator < (fruit f1,fruit f2)
    	{
    		return f1.peice < f2.price;
    	}
    };
    
  • 若希望水果价格低为优先级高

    //小顶堆
    struct fruit
    {
    	string name;
    	int price;
    	friend bool operator < (fruit f1,fruit f2)
    	{
    		return f1.peice > f2.price;  //此处是>
    	}
    };
    

### 2.仿函数

若希望水果价格高为优先级高,则若希望水果价格高为优先级高,则

//大顶堆
struct myComparison
{
	bool operator () (fruit f1,fruit f2)
	{
		return f1.price < f2.price;
	}
};

//此时优先队列的定义应该如下
priority_queue<fruit,vector<fruit>,myComparison> q;

此题代码如下:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
    //1.map记录元素出现的次数
        unordered_map<int,int>map;//两个int分别是元素和出现的次数
        for(auto& c:nums){
            map[c]++;
        }
    //2.利用优先队列,将出现次数排序
        //自定义优先队列的比较方式,小顶堆
        struct myComparison{
            bool operator()(pair<int,int>&p1,pair<int,int>&p2){
                return p1.second>p2.second;//小顶堆是大于号
            }
        };
        //创建优先队列
        priority_queue<pair<int,int>,vector<pair<int,int>>,myComparison> q;
        //遍历map中的元素
        //1.管他是啥,先入队列,队列会自己排序将他放在合适的位置
        //2.若队列元素个数超过k,则将栈顶元素出栈(栈顶元素一定是最小的那个)
        for(auto& a:map){
            q.push(a);
            if(q.size()>k){
               q.pop(); 
            }
        }
        //将结果导出
        vector<int>res;
        while(!q.empty()){
            res.emplace_back(q.top().first);
            q.pop();
        }
        return res;

    }
};
posted @ 2022-07-27 22:31  乐乐章  阅读(65)  评论(0编辑  收藏  举报