day17

1.剑指 Offer 40. 最小的 k 个数

 1 class Solution {
 2 public:
 3     vector<int> getLeastNumbers(vector<int>& arr, int k) {
 4       vector<int> res;
 5       sort(arr.begin(),arr.end());
 6       for(int i = 0;i < k;i ++)
 7        res.push_back(arr[i]);
 8       return res;
 9     }
10 };

2.剑指 Offer 41. 数据流中的中位数

优先队列,看k神题解

 1 class MedianFinder {
 2 public:
 3     /** initialize your data structure here. */
 4     priority_queue<int,vector<int>,greater<int>> A;//较大的部分,小顶堆
 5     priority_queue<int,vector<int>,less<int>> B;//较小的部分,大顶堆
 6     MedianFinder() {
 7 
 8     }
 9     
10     void addNum(int num) {
11        if(A.size() == B.size()){
12            B.push(num);
13            A.push(B.top());
14            B.pop();
15        }
16        else{
17            A.push(num);
18            B.push(A.top());
19            A.pop();
20        }
21     }
22     
23     double findMedian() {
24       return A.size() != B.size() ? A.top() : (A.top() + B.top()) / 2.0;
25     }
26 };
27 
28 /**
29  * Your MedianFinder object will be instantiated and called as such:
30  * MedianFinder* obj = new MedianFinder();
31  * obj->addNum(num);
32  * double param_2 = obj->findMedian();
33  */

 

posted @ 2022-07-13 17:33  balabalahhh  阅读(26)  评论(0)    收藏  举报