java using O(1)space,O(n)time


  • 0
    C
    public class Solution {
    public int thirdMax(int[] nums) {
        //flag
        boolean flag = false;
        //three loop
        if(nums.length<3)
        {
            if(nums.length==1)
                return nums[0];
            else
                return nums[0]>nums[1]?nums[0]:nums[1];
        }
        int Max = Integer.MIN_VALUE;
        int secondMax = Integer.MIN_VALUE;
        int thirdMax = Integer.MIN_VALUE;
        //get the Max
        for(int i=0;i<nums.length;i++)
        {
            Max = Max>nums[i]?Max:nums[i];
        }
        //get the secondMax
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i] == Max)
                continue;
            secondMax = secondMax>nums[i]?secondMax:nums[i];
        }
        //get the thirdMax
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i] == Max || nums[i] == secondMax)
                continue;
            thirdMax = thirdMax>nums[i]?thirdMax:nums[i];
            flag = true;
        }
        if(flag == false)
                return Max;
        return thirdMax;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.