LeetCode628 : Maximum Product of Three Numbers
题目大意
从所给数组中取三个数求其乘积并比较,返回最大的乘积
- Example1
Input: [1,2,3]
Output: 6
- Example2
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.
已给代码格式如下:
class Solution {
public:
int maximumProduct(vector<int>& nums) {
}
};
思路分析
由题知数组中的元素符号不定,且无序。因此我们应当先使用STL提供的sort函数对数组中元素进行排序。
例如一个数组的元素为:-4, 8,-2, 5, -12,1。排序后可得:-12,-8 , -2, 1 , 5 , 8。观察可知,最小的两个负数相乘获得两个负数乘积中最大的值,所以最大的三个数的值应当是最大的三个正数的乘积,或者最小的两个负数和最大的正数的乘积。因此,我们需要的就是对数组排序,并求出最大三个元素的乘积以及最小两个负数和最大正数的乘积,两者中更大的那个就是所求结果。
代码展示
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end()); //排序
//头文件:#include<algorithm>
int n = nums.size();
int result1 = nums[0]*nums[1]*nums[n-1];
int result2 = nums[n-1]*nums[n-2]*nums[n-3];
return result1>result2?result1:result2;
}
};
分析总结
该题最笨的方法是计算每三个数的乘积并进行比较获得最大值,但是提交后会显示“Time Limited Exceeded(超出时间限制)”,而且我们可以知道,对于中间的元素的计算是无用功,所以选择上面那种方法。ps:sort函数默认升序排列,两个参数分别为数组的始末位置。STL sort函数的详细解释