Flaw in Online judge and please find my python code in O(n) time and O(1) space


  • 0
    S

    The test cases such as [1,2,2] is not checked in such cases answer
    would be maximum whereas it passes in online judge

        def thirdMax(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if len(nums)==1:
                return nums[0]
            if len(nums)==2:
                return max(nums)
            max1=max(nums[0:3])   # FIRST DEAL WITH FIRST THREE NUMBERS OF ARRAY
            #print max1
            max2=float('-inf')
            max3=float('-inf')
            for i in range(0,3):
                if nums[i]>max2 and nums[i]!=max1:
                    max2=nums[i]
            for i in range(0,3):
                if nums[i]>max3 and nums[i]!=max1 and nums[i]!=max2:  #FIND MAX1,MAX2,MAX3 AMONG FIRST THREE NUMBERS
                    max3=nums[i]
            #print max2        
            #print max3
            
            if max3==float('-inf'):#IF THIRD MAX DOESN'T EXIST in FIRST THREE SAY [1,2,2]
                max3=max2                   
            # MAX3.....MAX2.....MAX1
            for i in range(0,len(nums)):      
                if nums[i]>max1: # MAX3.....MAX2.....MAX1....nums[i] update max3,max2,max1               
                    max3=max2
                    max2=max1
                    max1=nums[i]
                elif max2<nums[i]<max1:  # MAX3.....MAX2..nums[i]..MAX1 update max3,max2 
      max3=max2
                    max2=nums[i]
                elif max3<nums[i]<max2:  # MAX3..nums[i]...MAX2....MAX1 update max3 
                    max3=nums[i]
            if max1!=max2 and max2!=max3 and max3!=max1: # DEAL WITH DUPLICATES HERE SAY[1,2,2,2,2] CASES
                return max3
            else:
                return max(nums)

Log in to reply
 

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