• leetcode 628. Maximum Product of Three Numbers


    Given an integer array, find three numbers whose product is maximum and output the maximum product.

    Example 1:

    Input: [1,2,3]
    Output: 6
    

    Example 2:

    Input: [1,2,3,4]
    Output: 24
    

    Note:

      1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
      2. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

    这个题目本质上是一个数学题,需要细心观察才可以得到答案,考虑输入数据分布的几种情形:

    (1)全部是正数, 答案必然是最大的三个数组合。

    (2)全部是负数,答案和(1)同。

    (3)既存在正数,又存在负数的情形,数组排序后的结果分为三种情形:

    A、负,正,正,。。。=》最大数是三个最大数相乘。

    B、负,负,正,。。。=〉最大数是:max【(负x负x最大的正数),三个最大的正数相乘(如果有三个正数的话)】

    C、负,负,负,。。。正。。。。=》最大数和B同。

    因此,总结起来,结果就是:

            nums.sort()
            a = nums[-1] * nums[-2] * nums[-3]
            b = nums[0] * nums[1] * nums[-1]
            return max(a,b)

    本质上是贪心。这种题目专门考察思维的完备性。

    如果不用排序,则类似堆排序思想:

    class Solution(object):
        def maximumProduct(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            max3, max2, max1 = float('-inf'), float('-inf'), float('-inf')
            min2, min1 = float('inf'), float('inf')
            for n in nums:
                if n > max1:
                    if n > max3:
                        max3, max2, max1 = n, max3, max2
                    elif n > max2:
                        max3, max2, max1 = max3, n, max2
                    else:
                        max3, max2, max1 = max3, max2, n
                if n < min2:
                    if n < min1: min1, min2 = n, min1
                    else: min1, min2 = min1, n
            return max(max3*max2*max1, min1*min2*max3)

    可以用python里现有的库:

    class Solution(object):
        def maximumProduct(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums)
            return max(a[0] * a[1] * a[2], b[0] * b[1] * a[0])

    补充:

    >>> import heapq
    >>> nums=[21312,12211,211,3,12,212123]
    >>> heapq.nlargest(3, nums)
    [212123, 21312, 12211]
    >>> heapq.nsmallest(3, nums)
    [3, 12, 211]
  • 相关阅读:
    Servlet Filter
    Analysis of Web.xml in Hello1 project
    Introduction of Annotation
    Analysis of container and Injection in Java, their history and future.
    Maven + Glassfish 实现hello
    java Building tool
    HTTP RFC(自学心得)
    URI和URL
    Git 版本控制
    Oracle RAC 全局等待事件 gc current block busy 和 gc cr multi block request 说明--转载(http://blog.csdn.net/tianlesoftware/article/details/7777511)
  • 原文地址:https://www.cnblogs.com/bonelee/p/8727351.html
Copyright © 2020-2023  润新知