leet code - Third Maximum Number

来源:互联网 发布:一键获取淘宝联盟 编辑:程序博客网 时间:2024/06/05 02:54
题目描述
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;}}}


1 0
原创粉丝点击