【leetcode】414. Third Maximum Number

problem

414. Third Maximum Number

solution

思路:用三个变量first, second, third来分别保存第一大、第二大和第三大的数,然后遍历数组。

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        //1.LONG_MIN;
        long first = LONG_MIN, second = LONG_MIN, third = LONG_MIN;//
        for(auto a:nums)
        {
            if(a>first) 
            {
                if(second!=LONG_MIN) third = second;//判断.
                if(first!=LONG_MIN) second = first;
                first = a;
            }
            else if(a<first &&a>second && a!=first)
            {
                if(second!=LONG_MIN) third = second;
                second = a;
            }
            else if(a<second && a>third && a!=first && a!=second)
            {
                third = a;
            }
        }
        return (third==LONG_MIN)?first:third;
        
    }
};

注意:

1. 数据类型对应的最小值表示;

2. 赋值时需要判断是否为最小值;

参考

1. Leetcode_414. Third Maximum Number;

2. [leetcode] 414. Third Maximum Number 解题报告;

原文地址:https://www.cnblogs.com/happyamyhope/p/10466325.html