leetcode-628-Maximum Product of Three Numbers]

来源:互联网 发布:外星人笔记windows 编辑:程序博客网 时间:2024/06/06 02:45
class Solution {
public:
    int maximumProduct(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int a=nums.size();
        return nums[a-3]*nums[a-2]*nums[a-1];
    }

};



发现有负的,没辙,


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.

思路:

首先排序,然后分别判断数组元素最大值是正是负情况。

复制代码
  int maximumProduct(vector<int>& nums)  {    sort(nums.begin(),nums.end());    int len = nums.size();        int a,b,c;    c = nums[len-1];    b = nums[len-2];    a = nums[len-3];    if(a>0)return  max(nums[0]*nums[1]*c,a*b*c);    else if( a ==0 )    {      if(len==3)return 0;      if(len>=5)return nums[len-5]*nums[len-4]*c;//l两个负数      else return a*b*c;    }    else if(a<0)    {      if(c<0 )return a*b*c;      if(c>=0 &&b<0 )return nums[0]*nums[1]*c;      if(c>=0 && b>0 &&len>=4)return nums[0]*nums[1]*c;      if(c>=0 && b>0 &&len==3)return a*b*c;    }        return 0;  }  
复制代码

感觉写出来 超级啰嗦 惨不忍睹,于是看到了如下代码,

醍醐灌顶,五体投地。 排序过后,依次讨论前三个,后三个,以及后两个跟第一个,前两个跟最后一个。

复制代码
 public int maximumProduct(int[] nums) {            Arrays.sort(nums);            int n = nums.length;            int s = nums[n-1] * nums[n-2] * nums[n-3];            s = Math.max(s, nums[n-1] * nums[n-2] * nums[0]);            s = Math.max(s, nums[n-1] * nums[1] * nums[0]);            s = Math.max(s, nums[2] * nums[1] * nums[0]);            return s;        }
复制代码

发现上面的不行啊;

答案

class Solution {public:    int maximumProduct(vector<int>& nums) {        int len=nums.size();        sort(nums.begin(),nums.end());//将数组排序        int max1=nums[len-1]*nums[len-2]*nums[len-3];//计算第一种情况的最大值,为最后三个数        int max2=nums[0]*nums[1]*nums[len-1];//计算第二种情况的最大值为前两个数和最后一个数的乘积        return max1>max2?max1:max2;//返回两个中大的那个    }};


阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 寄生虫怎么检查 寄生虫病症状 胸部寄生虫 眼睛寄生虫 体外寄生虫 鱼类寄生虫 螃蟹寄生虫 血液寄生虫 寄生虫症状 黄鳝寄生虫 鲫鱼寄生虫 鱼的寄生虫 鱼身上的寄生虫 寄生虫病毒 脑部寄生虫 寄生虫是什么样子的 皮肤寄生虫 海鲜寄生虫 寄生虫检查 体内有寄生虫的症状 海螺寄生虫 寄生虫感染 蛇胆寄生虫 眼睛有寄生虫的症状 寄生虫高温能杀死吗 宠物寄生虫 人身上的寄生虫 海鲜有寄生虫吗 高温能杀死寄生虫吗 马蹄寄生虫 螳螂寄生虫 羊肉寄生虫 感染寄生虫的症状 什么是寄生虫 人类寄生虫 头发寄生虫 颅内寄生虫 鱼寄生虫 寄生虫皮肤病 动物寄生虫 寄生虫的症状