Third Maximum Number

题目来源
求数组中第3大的元素。
保存一个大小为3的vector,然后遍历,假如重复的跳过,假如大于最小的就替换,然后再排序,感觉处理起来还挺麻烦的。代码如下:

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        int n = nums.size();
        vector<int> top3;
        for (int i=0; i<n; i++) {
            bool rep = false;
            for (int j=0; j<top3.size(); j++)
                if (nums[i] == top3[j]) {
                    rep = true;
                    break;
                }
            if (rep)
                continue;
            if (top3.size() < 3)
                top3.push_back(nums[i]);
            else if (nums[i] > top3[0])
                top3[0] = nums[i];
            sort(top3.begin(), top3.end());
        }
        return top3.size() < 3 ? top3[top3.size()-1] : top3[0];
    }
};

看了看讨论区,一个简洁一点的做法如下:

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        set<int> top3;
        for (int num : nums) {
            top3.insert(num);
            if (top3.size() > 3) {
                top3.erase(top3.begin());
            }
        }
        return top3.size() == 3 ? *top3.begin() : *top3.rbegin();
    }
};

好吧,是简洁很多。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容