问题来源:https://leetcode.com/problems/third-maximum-number/
问题描述:
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.
我的代码(6ms):以下代码思路就是看到题目时最直观的思路,以前遍历一次可以找到最大值,那么遍历count次即可以找到第三大值,注意处理的就是数值重复以及数组中存在INT_MIN时的处理。第一次测试的时候最后一个测试[1, 1, INT_MIN]没有通过,由于设置的max是INT_MIN,所以需要设置push_back的进入条件(flag的设置)
int thirdMax(vector<int>& nums) {
int i, j, max_index;
int count = 3;//循环次数
vector<int> max_arr;//储存每次循环挑选出来的最大值
for (i = 0; i < count; i++){
bool flag = true;//标志max是否发生改变
int max = INT_MIN;//设置最小值
for (j = 0; j < nums.size(); j++){
if (nums[j] >= max){
max = nums[j];
flag = false;
max_index = j;
}
}
if (max_arr.size() > 0 && flag==false){
if (max == max_arr.back()){
count++;//如果重复 计数+1
}
else{
max_arr.push_back(max);
}
}
else if(flag==false){
max_arr.push_back(max);
}
if (nums.size() > 0){
nums.erase(nums.begin() + max_index);//去除当前最大值 重新循环
}
}
for (int k = 0; k < max_arr.size(); k++){
cout << max_arr[k] << endl;
}
if (max_arr.size() == 3){//存在第三大值
return max_arr.back();
}else{
return max_arr[0];
}
}
PS:补充取出vector的最后一位数值的三种方法:
int thirdMax(vector<int>& nums) {
long int fst = LONG_MIN, snd = LONG_MIN, trd = LONG_MIN;
for (int n : nums)
{
if (n == fst || n == snd || n == trd) continue;//跳过相同的数
if (n>fst)
{
trd = snd;
snd = fst;
fst = n;
}
else if (n>snd)
{
trd = snd;
snd = n;
}
else if (n>trd)
trd = n;
}
//cout <<"First:"<< fst << " Second:" << snd << " Third:" << trd << endl;
//cout << "The Result is " << (trd == LONG_MAX ? fst : trd) << endl;
return trd == LONG_MIN ? fst : trd;
}
果然差距还是大大的,第一次刷leetcode,不断总结不断加油吧~