zoukankan      html  css  js  c++  java
  • 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]
  • 相关阅读:
    解决多并发
    一个交换机到底能带几台摄像头?结合生产经验咱们来分析!
    ELK查询命令详解
    Ansible自动化部署入门到进阶笔记
    批量SSH key-gen无密码登陆认证脚本
    ELK查询命令详解总结
    Shell 正则表达式详解
    Linux 常用系统性能命令总结
    什么叫做消息队列呢?
    批量SSH key-gen无密码登陆认证脚本 附件脚本
  • 原文地址:https://www.cnblogs.com/bonelee/p/8727351.html
Copyright © 2011-2022 走看看