Leetcode—— 283 141 628. Maximum Product of Three Numbers

40 篇文章 0 订阅
19 篇文章 0 订阅

题目原址

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值