题目描述
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).
返回数组中第三大的数字,可能会包含重复。
思路:
直接遍历过程中存最大值求出结果。
public class Solution {
public int ThirdMax(int[] nums)
{
if(nums == null || nums.Length == 0){
throw new ArgumentException();
}
if(nums.Length == 1){
return nums[0];
}
if(nums.Length == 2){
return Math.Max(nums[0],nums[1]);
}
int max = nums[0];
for(var i = 1;i < nums.Length; i++){
if(nums[i] > max){
max = nums[i];
}
}
int? second = null;
for(var i = 0;i < nums.Length; i++){
if(nums[i] < max && (second == null || nums[i] > second)){
second = nums[i];
}
}
if(!second.HasValue){
return max;
}
int? third = null;
for(var i = 0;i < nums.Length; i++){
if(nums[i] < second && (third == null || nums[i] > third)){
third = nums[i];
}
}
if(third.HasValue){
return third.Value;
}
else{
return max;
}
}
}