leetcode 295+ lintcode 81 priority_queue

图片.png
#include
using namespace std;
#include
#include
#include
#include
#include
#include
#include 
#include 
#include 
//* Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//Definition for singly-linked list.
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };
//ans
class MedianFinder {
public:
    void addNum(int num) {
        small.push(num);
        large.push(-small.top());
        small.pop();
        if (small.size() < large.size()) {
            small.push(-large.top());
            large.pop();
        }
    }

    // Returns the median of current data stream
    double findMedian() {
        return small.size() > large.size() ? small.top() : 0.5 *(small.top() - large.top());
    }

private:
    priority_queue small, large;
};

//i81
class Solution {
private:
    priority_queue small, large;
public:
    void addNum(int num) {
        small.push(num);
        large.push(-small.top());
        small.pop();
        if (large.size() > small.size()) {
            small.push(-large.top());
            large.pop();
        }

    }
    double findMedian() {
        return small.top();
    }
    vector medianII(vector &nums) {
        vector ans;
        for (auto aa : nums) {
            addNum(aa);
            ans.push_back(findMedian());
        }
        return ans;
    }
};

int main()
{
    vector aa = { 1,2,22,1,3,1,1,7,8,5 };
    MedianFinder ss;
    double ans;
    ss.addNum(3);
    ans = ss.findMedian();
    ss.addNum(4);
    ans = ss.findMedian();
    ss.addNum(2);
    ans = ss.findMedian();
    ss.addNum(10);
    ans = ss.findMedian();
    ss.addNum(100);
    ans = ss.findMedian();
    //vector> ans(23, vector());

    getchar();
    return 0;
}
图片.png

你可能感兴趣的:(leetcode 295+ lintcode 81 priority_queue)