zoukankan      html  css  js  c++  java
  • 三个数的最大乘积

    三个数的最大乘积

    题目:
    给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。

    示例 1:

    输入: [1,2,3]
    输出: 6
    示例 2:

    输入: [1,2,3,4]
    输出: 24

    解题思路1:先对数组进行排序,然后发现答案有两种情况,如果有负数那么最大乘积可能是前两最小负数乘以最大正数,前三个最大正数乘积,对这三种情况进行比较即可

    
    class Solution {
        public int maximumProduct(int[] nums) {
            Arrays.sort(nums);
            
            int len = nums.length;
            int ans = 0;
            if(nums[0] < 0 && nums[1] < 0) {
                ans = Math.max(nums[0] * nums[1] * nums[2], Math.max(nums[0] * nums[1] * nums[len - 1], nums[len - 1] * nums[len - 2] * nums[len - 3]));
            } else {
                ans = nums[len - 1] * nums[len - 2] * nums[len - 3];
            }
            
            return ans;
        }
    }
    

    解题思路2:先别找出数组中最小的两个数和最大的三个数,然后对他们的乘积进行比较即可

    class Solution {
        public int maximumProduct(int[] nums) {
            
            int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE, max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, 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);
        }
    }
    
  • 相关阅读:
    多表查询
    Java基础
    group by 和 having 用法
    多态
    修改用户权限
    集成测试过程
    系统测试
    软件验收测试通过准则
    性能测试、负载测试、压力测试的区别
    白盒测试
  • 原文地址:https://www.cnblogs.com/katoMegumi/p/14301228.html
Copyright © 2011-2022 走看看