题目原址
https://leetcode.com/problems/maximum-product-of-three-numbers/description/
题目描述
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example2:
Input: [1,2,3,4]
Output: 24
Note:
- The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
- Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.
解题思路
题目的意思是:
- 给一个数组,找出数组中三个数相乘结果最大的值,但是要注意它Note的第一点,数组的范围是
[-1000,1000]
因此这里需要小心,因为可能两个最小的负数相乘的结果比最大的两个正数的相乘结果更大。 - 该题的一个作弊做法就是使用Array.sort()方法对数组进行排序,只需要两行代码就搞定。
- 常规的做法是依次遍历数组,找到5个特殊值,即最小的两个数和最大的三个数,最后返回max(最大三个数乘积,最小两个数*最大的正数)。
AC代码
class Solution {
public int maximumProduct(int[] nums) {
int min1 = Integer.MAX_VALUE; //倒数第二小
int min2 = Integer.MAX_VALUE; //最小
int max1 = Integer.MIN_VALUE; //倒数第三大
int max2 = Integer.MIN_VALUE; //倒数第二大
int max3 = Integer.MIN_VALUE; //最大
for(int i : nums) {
if(i > max3) {
max1 = max2;
max2 = max3;
max3 = i;
}else if(i > max2) {
max1 = max2;
max2 = i;
}else if(i > max1){
max1 = i;
}
if(i < min2){
min1 = min2;
min2 = i;
}else if(i < min1){
min1 = i;
}
}
return Math.max(min1 * min2 * max3 , max1 * max2 * max3);
}
}
感谢
https://discuss.leetcode.com/topic/93804/java-o-1-space-o-n-time-solution-beat-100