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)的时间复杂度下,在一个非空的数组里找第三大的数字,如果没有第三大的数字就返回最大的数字,如果像1,2,3,2这种数据的话,1才是第3大的数字。
思路:开辟一个最大size为3的辅助空间,保存最大的3个数字(遍历数组时将当前数字a和辅助空间中的最小的数字b比较,如果比a>b那么就将b替换为a,O(3n)),然后将辅助空间排序(O(1)),最后判断辅助空间的size是否为3,如果是3就返回第三大的数字,否则返回最大数字。
public class ThirdMaximumNumber {
public int thirdMax(int[] nums) {
ArrayList<Integer> back = new ArrayList<Integer>();
for(int value:nums)
{
if(!back.contains(value))
{
//不够就加
if(back.size() < 3)
{
back.add(value);
continue;
}
//替换最小的
int minIndex = 0;
int minValue =Integer.MAX_VALUE;
for(int i = 0; i < back.size(); ++i)
{
if(back.get(i) < minValue)
{
minIndex = i;
minValue = back.get(i);
}
}
if(value > minValue)
back.set(minIndex, value);
}
}
//升序排序
back.sort(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2)
{
if(o1>o2)
{
return 1;
}
else if(o1 < o2)
return -1;
return 0;
}
});
if(back.size() <3)
{
return back.get(back.size()-1);
}
return back.get(0);
}
}