(Easy) Third Maximum Number LeetCode

Description:

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.

 

 

Solution:

class Solution {
    public int thirdMax(int[] nums) {
        if(nums==null||nums.length<=0){
            return 0;
        }
        
        Arrays.sort(nums);
        int max_real =  nums[nums.length-1];
        int max = nums[nums.length-1];
    
        
        int k = 3; 
        int third=0;
        
        for( int i =nums.length-1; i>=0 && k>=1; i--){
         System.out.println(i);
            if(nums[i]<max){
                max = nums[i];
                k=k-1;
                
            }
            
            if(k ==1){
                
                  third = nums[i];
                 return third;
            }
            
           
        }
        
        return max_real;
    }
}

 

posted @ 2019-08-12 18:56  CodingYM  阅读(110)  评论(0编辑  收藏  举报