Third Maximum Number

注意这里题目的要求是重复数只算一次,所以比较大小时不能带上等于号

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n < 3:
            return max(nums)

        first, second, third = -sys.maxint, -sys.maxint, -sys.maxint
        for i in xrange(n):
            if nums[i] > first:
                third = second
                second = first
                first = nums[i]
            elif second < nums[i] < first:
                third = second
                second = nums[i]
            elif third < nums[i] < second:
                third = nums[i]
        return third if third != -sys.maxint else first

results matching ""

    No results matching ""