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.
此题不难,但很离奇wa很多遍,贴上记录之。
class Solution {
public:
int thirdMax(vector<int>& nums) {
int len=nums.size();
if(len==1)
return nums[0];
if(len==2)
return max(nums[0],nums[1]);
int a=INT_MIN,b=INT_MIN,c=INT_MIN;
int num=0;
int flag=0;
for(int i=0;i<len;i++)
{
if(nums[i]>a)
{
c=b;
b=a;
a=nums[i];
}
else if(nums[i]==a)
{
if(a==INT_MIN)
flag=1;
continue;
}
else if(nums[i]>b)
{
c=b;
b=nums[i];
}
else if(nums[i]==b)
{
if(b==INT_MIN)
flag=2;
continue;
}
else if(nums[i]>=c)
{
c=nums[i];
num=1;
}
}
if(flag>0&&b>INT_MIN&&c==INT_MIN)
return c;
if(num==0&&c==INT_MIN)
return a;
else
return c;
}
};