题目描述:
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.
找到数组中不重复的第三小的数字(数值相同的元素不重复计算),要求时间复杂度为O(n),还可以只用常数空间,只需要维护三个变量表示最小的数、第二小的数和第三小的数,每次遍历到一个元素,就更新这三个变量。
class Solution {
public:
int thirdMax(vector<int>& nums) {
long a=LONG_MIN;
long b=LONG_MIN;
long c=LONG_MIN;
bool exist=false;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>a)
{
c=b;
b=a;
a=nums[i];
}
else if(nums[i]<a&&nums[i]>b)
{
c=b;
b=nums[i];
}
else if(nums[i]<b&&nums[i]>c)
{
c=nums[i];
}
}
if(c==LONG_MIN) return a;
else return c;
}
};