呓语Beta 2.0 首页 镜头后 灶台前 捐赠者名单 有趣的小站

leetcode 628 Maximum Product Of Three Numbers

文档信息

leetcode 628 Maximum Product Of Three Numbers

解法一:

class Solution(object):
    def maximumProduct(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    s = sorted(nums)[::-1]
    if s[2] > 0:
        return s[0]*(max(s[1]*s[2], s[-1]*s[-2]))
    elif s[2] <= 0:
        return s[0]*s[-1]*s[-2]
    elif s[1] <= 0:
        return s[0]*s[-1]*s[-2]
    elif s[0] <= 0:
        return s[0]*s[1]*s[2]

note

优化解法一:

class Solution(object):
    def maximumProduct(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    s = sorted(nums, reverse=True)
    if s[2] > 0:
        return s[0]*max(s[1]*s[2], s[-1]*s[-2])
    elif s[0] <= 0:
        return s[0]*s[1]*s[2]
    else:
        return s[0]*s[-1]*s[-2]

note

捐赠支持

可以使用支付宝转帐给richard.ma.19850509#gmail.com(请将#替换为@),谢谢!

Fork me on GitHub