Leetcode 414. Third Maximum Number

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 414. Third Maximum Number_第1张图片
Third Maximum Number

2. Solution

  • Version 1
class Solution {
public:
    int thirdMax(vector& nums) {
        long long first = LLONG_MIN;
        long long second = LLONG_MIN;
        long long third = LLONG_MIN;
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] <= third || nums[i] == first || nums[i] == second) {
                continue;
            }
            if(nums[i] > first) {
                third = second;
                second = first;
                first = nums[i];
            }
            else if(nums[i] > second) {
                third = second;
                second = nums[i];
            }
            else {
                third = nums[i];
            }
        }
        if(third == LLONG_MIN) {
            return first;
        }
        return third;
    }
};
  • Version 2
class Solution {
public:
    int thirdMax(vector& nums) {
        set values(nums.begin(), nums.end());
        if(values.size() < 3) {
            return *values.rbegin();
        }
        values.erase(--values.end());
        values.erase(--values.end());
        return *(--values.end());
    }
};

Reference

  1. https://leetcode.com/problems/third-maximum-number/description/

你可能感兴趣的:(Leetcode 414. Third Maximum Number)