首页 > 代码库 > 【42】414. Third Maximum Number

【42】414. Third Maximum Number

414. Third Maximum Number

Description Submission Solutions Add to List

  • Total Accepted: 20624
  • Total Submissions: 76932
  • Difficulty: Easy
  • Contributors: ZengRed , 1337c0d3r

 

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: 1

Explanation: The third maximum is 1.

 

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

 

Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.


 1 class Solution {
 2 public:
 3     int thirdMax(vector<int>& nums) {
 4         long first = LONG_MIN, second = LONG_MIN, third = LONG_MIN;//初始化要用长整型long的最小值,否则当数组中有INT_MIN存在时,程序就不知道该返回INT_MIN还是最大值first了
 5         for(int i = 0; i < nums.size(); i++){
 6             if(nums[i] > first){//update 3 个
 7                 third = second;
 8                 second = first;
 9                 first = nums[i];
10             }else if(nums[i] > second && nums[i] < first){//update second & third
11                 third = second;
12                 second = nums[i];
13             }else if(nums[i] > third && nums[i] < second){
14                 third = nums[i];
15             }
16         }
17         /*
18         if(third == INT_MIN){
19             return second == INT_MIN ? first : second;
20         }
21         return third;*/
22         return (third == LONG_MIN || third == second) ? first : third;
23     }
24 };

 

















【42】414. Third Maximum Number