IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]leet code - Third Maximum Number

    csharp25发表于 2016-10-31 22:30:50
    love 0
    题目描述
    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;
    		}
    		
    	
    	}
    	
    
    
    
    
    }




沪ICP备19023445号-2号
友情链接