给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
1. 排序后返回
int thirdMax(vector<int>& nums) {
sort(nums.begin(),nums.end());
nums.erase(unique(nums.begin(),nums.end()),nums.end());
int num = nums.size();
if(num<=2)
return nums[num-1];
else
return nums[num-3];
}
2. 使用set
int thirdMax(vector<int>& nums) {
set<int> s(nums.begin(),nums.end());
auto it=s.rbegin();
if(s.size()<3)
{
return *it;
}
else
{
return *(++(++it));
}
}
//维护规模为3的set
int thirdMax(vector<int>& nums) {
set<int> hash_set;
for(auto n:nums){
hash_set.insert(n);
if(hash_set.size()>3)
hash_set.erase(*(hash_set.begin()));//set中只留三个数字
}
if(hash_set.size()<3)
return *(hash_set.rbegin());
else
return *(hash_set.begin());
}
3. 维护三个数字
int thirdMax(vector<int>& nums) {
long first = LONG_MIN, second = LONG_MIN, third = LONG_MIN;
for (const auto &n : nums) {
if (n > first) {
third = second;
second = first;
first = n;
} else if (n > second && n < first) {
third = second;
second = n;
} else if (n > third && n < second) {
third = n;
}
}
return third == LONG_MIN ? first : third;
}
4. 使用指针
int thirdMax(vector<int>& nums) {
int *max1 = nullptr, *max2 = nullptr, *max3 = nullptr;
for (int i=0; i<nums.size(); ++i){
if (max1 == nullptr || nums[i] > *max1){
max3 = max2;
max2 = max1;
max1 = &nums[i];
}
else if (nums[i] == *max1)
continue;
else if (max2 == nullptr || nums[i]>*max2){
max3 = max2;
max2 = &nums[i];
}
else if (nums[i] == *max2)
continue;
else if (max3 == nullptr || nums[i]>*max3)
max3 = &nums[i];
}
if (max3 == nullptr)
return *max1;
return *max3;
}