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

    思路:给出一个数组找出里面三个元素乘积的最大值并输出。先对整个数组进行排序,考虑到有负数的情况,因此,三个数的乘积有两种情况,2负1正,或者3个正数,如果只三个数便直接输出。

    自己代码:

    1 int maximumProduct(vector<int>& nums) {
    2         sort(nums.begin(), nums.end());
    3         int n = nums.size();
    4         if(nums[0] < 0 && nums[1] < 0 && nums[0]*nums[1]*nums[n-1] > nums[n-1]*nums[n-2]*nums[n-3])
    5                 return nums[0]*nums[1]*nums[n-1];
    6         else 
    7            return nums[n-1] * nums[n-2] * nums[n-3]; 
    8     }

    优秀代码:

    1 int maximumProduct(vector<int>& nums) {
    2         sort(nums.begin(), nums.end());
    3         int n = nums.size();
    4         int m1 = nums[0]*nums[1]*nums[n-1];
    5         int m2 = nums[n-1] * nums[n-2] * nums[n-3]; 
    6         return m1 > m2?m1:m2;  //或者 return max(m1, m2);
    7     }

    其实不用检验前面两个元素是否是负数,因为只有两种情况,前面两个,后面一个,或者后面三个。

  • 相关阅读:
    datatime,time,string转换和format格式化处理
    迭代器和生成器进一步的认识
    对数据结构的新认识
    python StringIO中的 read()与 getvalue()
    git 分支策略
    js词法分析
    js作用域
    注解
    MapReduce过程详解(基于hadoop2.x架构)
    指数基金
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7345996.html
Copyright © 2011-2022 走看看