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     }

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

  • 相关阅读:
    面向对象诠释图
    vs中web网站和web应用程序的区别
    基于Windows Mobile 5.0的GPS应用程序开发
    c#添加水印效果
    基于Silverlight4开发的相关工具
    WCF、Net remoting、Web service概念及区别
    数据库的相关经验总结
    SQLite 3 一些基本的使用
    PPC上网设置明细图文并茂
    正则表达式语法参考
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7345996.html
Copyright © 2011-2022 走看看