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.

 

要完成的函数:

int maximumProduct(vector<int>& nums) 

 

说明:

1、这道题目给了一个vector,要求返回一个最大值,这个最大值由vector中的三个元素相乘得到。

如果vector中只有正数,那么没有疑问,最大值由最大的三个元素相乘得到。

但如果vector中有负数,那么最大值也有可能由两个最小的负数乘以最大的正数得到。

但是无论如何,要不就是三个最大的正数相乘得到,要不就是两个最小的负数乘以最大的正数得到,不可能由中间的数相乘得到。

思路很清晰,代码如下:

    int maximumProduct(vector<int>& nums) 
    {
        sort(nums.begin(),nums.end());
        int a=nums[0]*nums[1]*nums[nums.size()-1];//俩最小负数乘以最大正数
        int b=nums[nums.size()-1]*nums[nums.size()-2]*nums[nums.size()-3];//三个最大的正数
        return a>b?a:b;
    }

上述代码实测69ms,beats 44.94% of cpp submissions。

2、改进:

其实我们不需要全排整个vector,我们只要部分排序之后的第一位、第二位、倒数第一位、倒数第二位以及倒数第三位的值。

所以使用nth_element来处理。代码如下:

    int maximumProduct(vector<int>& nums) 
    {
        int s1=nums.size();
        nth_element(nums.begin(),nums.begin(),nums.end());
        int a=nums[0];
        nth_element(nums.begin(),nums.begin()+1,nums.end());
        int b=nums[1];
        nth_element(nums.begin(),nums.end()-1,nums.end());
        int c=nums[s1-1];
        nth_element(nums.begin(),nums.end()-2,nums.end());
        int d=nums[s1-2];
        nth_element(nums.begin(),nums.end()-3,nums.end());
        int e=nums[s1-3];

        int f=c*d*e;
        int g=a*b*c;
        return f>g?f:g;
    }

上述代码实测56ms,beats 74.16% of cpp submissions。

猜你喜欢

转载自www.cnblogs.com/king-3/p/9022532.html