难度简单248
给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例 1:
输入: [1,2,3] 输出: 6
示例 2:
输入: [1,2,3,4] 输出: 24
注意:
- 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
- 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。
思路1:本质是找到最大的三个数和最小的两个数来操作
解答成功:
执行耗时:12 ms,击败了69.60% 的Java用户
内存消耗:40 MB,击败了28.63% 的Java用户
class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
//三种情况,1.全是非负数。2.全是非正数。3.有正有负
int res=0;
int len=nums.length;
//1,2 情况是直接取排序后最大的三个数相乘,
res=nums[len-1]*nums[len-2]*nums[len-3];
//3.情况是取到两个最小负数和最大的正数和之前的数做比较
res = Math.max(nums[0]*nums[1]*nums[len-1],res);
return res;
}
}
思路2:
用5个数来存储上面介绍的5个值。
解答成功:
执行耗时:3 ms,击败了81.59% 的Java用户
内存消耗:39.9 MB,击败了44.23% 的Java用户
class Solution {
public int maximumProduct(int[] nums) {
int max1=Integer.MIN_VALUE,max2=Integer.MIN_VALUE,max3=Integer.MIN_VALUE;
int min1=Integer.MAX_VALUE,min2=Integer.MAX_VALUE;
int temp=0,temp1=0;
for (int i = 0; i < nums.length; i++) {
temp=nums[i];
if(temp>max3){
temp1=max3;
max3=temp;
temp=temp1;
}
if(temp>max2){
temp1=max2;
max2=temp;
temp=temp1;
}
if(temp>max1){
temp1=max1;
max1=temp;
temp=temp1;
}
temp = nums[i];
if(temp<min1){
temp1=min1;
min1=temp;
temp=temp1;
}
if(temp<min2){
temp1=min2;
min2=temp;
temp=temp1;
}
}
int len=nums.length;
return Math.max(max1*max2*max3,min1*min2*max3);
}
}