P9-三个数的最大乘积-线性扫描
//三个数的最大乘积 /* * 整型数组nums,在数组中找出由三个数字组成的最大乘积,并输出这个乘积。默认不会越界 * */ public class P9 { public static void main(String[] args) { // System.out.println(sort(new int[]{1,2,3,4,5,6})); System.out.println(getMaxMin(new int[]{-2,-1,3,4,5})); System.out.println(getMaxMin(new int[]{-5,-4,1,2,3})); } /* * 如果全是正数,找出三个最大的数就可以 * 如果全是负数,同样找出三个最大的数就可以 * 如果有正有负,要找出最大的正数和,绝对值最大的两个负数,或者是三个最大正数 * (-2,-1,3,4,5)(-5,-4,1,2,3) * */ //时间复杂度高,O(NlogN) 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-1] * nums[n-2] * nums[n-3]); //如果是有正有负,第一个数一定是绝对值最大的负数 } //线性扫描,O(n) //要找出最大的三个值,和最小的两个值,找出这5个值就可以像上方那样比较 public static int getMaxMin(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 x : nums){ if(x < min1){ min2 = min1; min1 = x; }else if(x < min2){ min2 = x; } if(x > max1){ max3 = max2; max2 = max1; max1 = x; }else if(x > max2){ max3 = max2; max2 = x; }else if(x > max3){ max3 = x; } } return Math.max(min1 * min2 * max1, max1 * max2 * max3); } }