Leetcode 414 Third Maximum Number

why pick the long.MIN_VALUE ?

beacuse, there is case [1,2, Integer.MIN_VALUE] can not pass it with picking Integer.MIN_VALUE;

Follow up what if pick third maxium value in long range rather than integer

--How to initialzie the three max variable

--how can sacn one time to update the three variable? always start from the maxium one and update the max2 and max3 at the same time.

class Solution {
    public int thirdMax(int[] nums) {
        /*if(nums.length == 2){
            return nums[0] > nums[1] ?nums[0] : nums[1];
        }else if(nums.length == 1){
            return nums[0];
        }*/
        //why pick long value
        long max1 = Long.MIN_VALUE;
        long max2 = Long.MIN_VALUE;
        long max3 = Long.MIN_VALUE; 
        //case with 3,2,2
        //scan one times checking three elements
        for(int i = 0; i<nums.length; i++){
            if(nums[i] > max1){
                max3 = max2;
                max2 = max1;
                max1 = nums[i];
            }else if(nums[i]<max1 && nums[i]>max2){
                max3 = max2;
                max2 = nums[i];
            }else if(nums[i]<max2 && nums[i] > max3){
                max3 = nums[i];
            }
            
        }
        if(max3==Long.MIN_VALUE ){
            return (int)max1;
        }else return (int)max3;
        
        //System.out.println(max1);
        //System.out.println(0xffffffff);
        
        //return 1;
    }
}

猜你喜欢

转载自www.cnblogs.com/stiles/p/Leetcode414.html