LeetCode 414 Third Maximum Number(set + priority_queue)

来源:互联网 发布:linux screen 切换 编辑:程序博客网 时间:2024/05/18 10:40

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]Output: 1Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]Output: 1Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.
题目大意:给出一个非空的整型数组,编写程序返回第三大的数字。如果没有第三大的数字则返回最大的数字。

解题思路:因为数字有可能重复,所以用set维护已经出现的数字,然后再用优先队列来维护数组最大值和第三大的值。

代码如下:

class Solution {public:    int thirdMax(vector<int>& nums) {        for(auto a : nums){            if(st.count(a) == 0){                pque.push(a);                st.insert(a);            }        }        int thirdMax = pque.top();        if((int)st.size() >= 3) {            pque.pop();            pque.pop();            thirdMax = pque.top();        }        return thirdMax;    }private:    priority_queue<int> pque;    set<int> st;};

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 混合喂养宝宝便秘怎么办 混合喂养不吃奶瓶怎么办 混合喂养厌奶粉怎么办 气血虚奶水少怎么办 产后奶水不足怎么办啊 婴儿吐奶瓣和水怎么办 一岁半宝宝频繁喝夜奶怎么办 婴儿腹泻不吃奶怎么办 八个月宝宝脱水怎么办 宝宝呕吐脱水了怎么办 宝宝腹泻没精神怎么办 小孩拉稀没精神怎么办 宝宝拉稀脱水了怎么办 宝宝发烧还拉肚子怎么办 宝宝发烧后腹泻怎么办 吃海鲜拉肚子了怎么办 孕妇吃海鲜腹泻怎么办 稀饭煮焦了怎么办 8月宝宝拉肚子怎么办 满月宝宝38度怎么办 未满月婴儿拉稀怎么办 未满月宝宝拉稀怎么办 满月的宝宝拉稀怎么办 十个月小孩拉肚子怎么办 十个月宝宝脱水怎么办 宝宝拉肚子老不好怎么办 孩子拉稀老不好怎么办 宝宝拉肚子发呕怎么办 刚出生婴儿拉肚子怎么办 宝宝一岁拉肚子怎么办 刚出生宝宝拉肚子怎么办 宝宝出生五天拉肚子怎么办 生完宝宝拉肚子怎么办? 宝宝6天拉肚子怎么办 十天婴儿拉肚子怎么办 十天小孩拉肚子怎么办 肠炎宝宝一直吐怎么办 初生婴儿老打嗝怎么办 小孩一直发低烧怎么办 婴儿喷奶严重怎么办 婴儿吃奶粉漾奶怎么办