zoukankan      html  css  js  c++  java
  • 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.

    理很明白,逻辑没弄清.
    想法是:找出 top3 最大, top2 最小, 一趟找出, 关键是逻辑.
    形象一些讲就是: 孩子们长身体,老大穿不了的衣服传给老二,老二穿不了的传给老三,老三找到合适衣服直接穿上.

    人家逻辑:
    (O(n)) time, (O(1)) extra space.

    int maximumProduct(vector<int>& A) {
        int m1 = INT_MIN, m2 = INT_MIN;
        int m3 = INT_MIN, s1 = INT_MAX, s2 = INT_MAX, res, i, v;
    
        //孩子们长身体,老大穿不了的衣服传给老二,老二穿不了的传给老三.
        for (i = 0; i < A.size(); i++) {
            v = A[i];
            if (v > m1) {m3 = m2; m2 = m1; m1 = v;}
            else if (v > m2) {m3 = m2; m2 = v;}
            else if (v > m3) {m3 = v;}
    
            if (v < s1) {s2 = s1; s1 = v;}
            else if (v < s2) {s2 = v;}
        }
        res = m1 * m2 * m3 > m1 * s1 * s2 ? m1 * m2 * m3 : m1 * s1 * s2;
        return res;
    }
    
  • 相关阅读:
    java 集合框架
    java 迭代器遍历List Set Map
    java 容器 List
    OpenLayer4实现卷帘效果
    python结合百度api进行地理编码和爬取POI点
    ArcGIS API For JS空间参考系的浅析
    OpenLayer4加载svg
    OpenLayer3动态点线和动态点的扩散实现
    LeaFlet学习之地图文字标注
    装饰器设计模式
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7366401.html
Copyright © 2011-2022 走看看