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

    三个数的最大乘积

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

    示例 1:

    输入: [1,2,3]

    输出: 6

    示例 2:

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

    输出: 24

    注意:

    1. 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
    2. 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。

    思路

     

    1 public class Solution {
    2     public int maximumProduct(int[] nums) {
    3         Arrays.sort(nums);
    4         return Math.max(nums[0] * nums[1] * nums[nums.length - 1], nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]);
    5     }
    6 }

     

     

     

    思路

     1 public class Solution {
     2     public int maximumProduct(int[] nums) {
     3         int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
     4         int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
     5         for (int n: nums) {
     6             if (n <= min1) {
     7                 min2 = min1;
     8                 min1 = n;
     9             } else if (n <= min2) {     // n lies between min1 and min2
    10                 min2 = n;
    11             }
    12             if (n >= max1) {            // n is greater than max1, max2 and max3
    13                 max3 = max2;
    14                 max2 = max1;
    15                 max1 = n;
    16             } else if (n >= max2) {     // n lies betweeen max1 and max2
    17                 max3 = max2;
    18                 max2 = n;
    19             } else if (n >= max3) {     // n lies betwen max2 and max3
    20                 max3 = n;
    21             }
    22         }
    23         return Math.max(min1 * min2 * max1, max1 * max2 * max3);
    24     }
    25 }

  • 相关阅读:
    5月编程语言排行榜:动态语言的前世今生
    编程语言范式
    面向函数范式编程(Functional programming)
    bash脚本测试总结
    BASH的保护性编程技巧
    汇编Shellcode的技巧
    FreeBSD上编写x86 Shellcode初学者指南
    CnAms and cndoc
    Linux下shellcode的编写
    How To Configure NetScaler AppFlow for SolarWinds
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10381432.html
Copyright © 2011-2022 走看看