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.
easy 题目基本没什么算法可言。找三个最大的数,注意不够三个数的情况(没有出现三个及以上数值不同的数) 以及在数组中出现MIN_VALUE的情况
bugfree需要强化,在每次写之前都把能想到的corner写下来 写完程序之后对照一遍这些坑有没有漏
public class Solution {
public int thirdMax(int[] nums) {
int min1=Integer.MIN_VALUE;
int min2=Integer.MIN_VALUE;
int min3=Integer.MIN_VALUE;
boolean flag=false;
for(int i=0;i<nums.length;i++){
if(nums[i]==Integer.MIN_VALUE)
flag=true;
if(nums[i]==min1||nums[i]==min2||nums[i]==min3)
continue;
if(nums[i]>min3){
min3=nums[i];
}
if(min3>min2){
int temp=min2;
min2=min3;
min3=temp;
}
if(min2>min1){
int temp=min1;
min1=min2;
min2=temp;
}
}
if(min3!=Integer.MIN_VALUE||(flag&&min2!=Integer.MIN_VALUE))
return min3;
else return min1;
}
}