414 Third Maximum Number

Given a non-empty array, return the third largest number in this array. If it does not exist, returns the largest number in the array. The time complexity of the algorithm is required to be O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third largest number is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third largest number does not exist, so return The largest number 2.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the request to return the third largest number refers to the third largest and unique number.
There are two numbers with the value 2, both of which come second.
See: https://leetcode.com/problems/third-maximum-number/description/
C++:

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        long first = LONG_MIN, second = LONG_MIN, third = LONG_MIN;
        for (int num : nums)
        {
            if (num > first)
            {
                third = second;
                second = first;
                first = num;
            }
            else if (num > second && num < first)
            {
                third = second;
                second = num;
            }
            else if (num > third && num < second)
            {
                third = num;
            }
        }
        return (third == LONG_MIN || third == second) ? first : third;
    }
};

 Reference: https://www.cnblogs.com/grandyang/p/5983113.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324499388&siteId=291194637