给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
示例 1:
输入: [3, 2, 1] 输出: 1 解释: 第三大的数是 1.
示例 2:
输入: [1, 2] 输出: 2 解释: 第三大的数不存在, 所以返回最大的数 2 .
示例 3:
输入: [2, 2, 3, 1] 输出: 1 解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。 存在两个值为2的数,它们都排第二。
class Solution {
public:
int thirdMax(vector<int>& nums) {
int res;
//先排序
sort(nums.begin(),nums.end());
//去重
vector<int>::iterator iter = unique(nums.begin(), nums.end());
nums.erase(iter,nums.end());
int size = nums.size();
if(size < 3)
return res = nums.back();
else
return res = nums[size - 3];
}
};
但是我这样写并不能满足时间复杂度,因为排序的时间复杂度是O(nlogn) > O(n),因此我参照了一个比较好理解的参考样例。指定one,two,three代表第1,2,3大,然后在一套循环中进行比较,只需要历遍一次,就能把1,2,3大找到。
然后,如果3大是哨兵值,就说明数组长度没有3,那么输出1大。(因为3大和2大不可能一样,因为判断中都是严格大于小于,是不存在大于等于之类的。)
class Solution {
public:
int thirdMax(vector<int>& nums)
{
long long one,two,three;
const long long MINN=-3147483648;
one=MINN;
two=MINN;
three=MINN;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>one)
{
three=two;
two=one;
one=nums[i];
}
else if(nums[i]>two&&nums[i]<one)
{
three=two;
two=nums[i];
}
else if(nums[i]>three&&nums[i]<two) three=nums[i];
}
if(three==MINN) return(int(one));
else return(int(three));
}
};