【算法面试题】数组中三个数的最大乘积
1.要求:
1.整型数组nums,在数组中找出由三个数字组成的最大乘积,并输出这个乘积。
2.乘积不会越界。
3.重点考察:线性扫描。
2.问题分析
1.数组元素全部为正数,三个数的最大乘积就是最大的三个数相乘。
2.数组元素全部为正数,三个数的最大乘积也是最大的三个数乘积。
例如 -4、-3、-2、-1。最大数就是(-3 * -2 * -1)。
3.数组元素有正数有负数,三个数的最大乘积就是最小的两位数乘于最大的那位数
例如:-4、-3、-2、3、6、8、9。最大数就是(-4 * -3 *9)。
1、2视为一种情况,三是一种情况,因此只需要比较两种情况的数值,输出数值最大的那个。
3.第一种写法
public class MaxProduct {
public static void main(String[] args) {
System.out.println(sort(new int[]{7,5,6,0,7,6}))
}
public static int sort(int[] nums){
Arrays.sort(nums);//排序
int n = nums.length;
return Math.max(nums[0] * nums[1] * nums[n-1], nums[n-3] * nums[n-2] * nums[n-1])
}
}
3.1第一种写法缺点
时间复杂度太大: O(N*log2N)
4.第二种写法
public class MaxProduct {
public static void main(String[] args) {
System.out.println(getMaxMin(new int[]{7,5,6,0,7,6}));
}
public static int getMaxMin(int[] nums){
int min1 = Integer.MAX_VALUE,min2 = Integer.MAX_VALUE;
int max1 = Integer.MIN_VALUE,max2 = Integer.MIN_VALUE,max3 = Integer.MIN_VALUE;
//线性扫描
for (int i = 0; i < nums.length; i++) {
if(nums[i] < min1){
min2 = min1;
min1 = nums[i];
}else if(nums[i] < min2){
min2 = nums[i];
}
if(nums[i] > max1){
max3 = max2;
max2 = max1;
max1 = nums[i];
}else if(nums[i] > max2){
max3 = max2;
max2 = nums[i];
}else if(nums[i] > max3){
max3 = nums[i];
}
}
return Math.max(min1 * min2 * max1, max1 * max2 * max3);
}
}
4.1第二种写法优势
时间复杂度小:O(N)。
5.输出结果
6.总结
本题使用线性扫描算法,时间复杂度更小,省了排序的时间。