博客
关于我
线性扫描--求数组中三个数最大乘积
阅读量:334 次
发布时间:2019-03-04

本文共 1244 字,大约阅读时间需要 4 分钟。

package solution.study;import java.util.Arrays;/** * Created by Anjude * Date: 2021/4/18 23:28 * 注意数组中可能出现负数 */public class MaxProduct {       public static void main(String[] args) {           System.out.println(sort(new int[]{   1, 2, 3, 4, 5, 6}));        System.out.println(getMaxMin(new int[]{   1, 2, 3, 4, 5, 6}));    }    // 线性扫描    private static int getMaxMin(int[] nums) {           int min1 = Integer.MAX_VALUE, min2 = min1;        int max1 = Integer.MIN_VALUE, max2 = max1, max3 = max1;        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);    }    private 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]);    }}

转载地址:http://wnhh.baihongyu.com/

你可能感兴趣的文章
MySQL常见的三种存储引擎(InnoDB、MyISAM、MEMORY)
查看>>
MySQL常见的三种存储引擎(InnoDB、MyISAM、MEMORY)
查看>>
MySQL常见约束条件
查看>>
MySQL常见错误
查看>>
MySQL常见错误分析与解决方法总结
查看>>
mysql并发死锁案例
查看>>
MySQL幻读:大家好,我是幻读,我今天又被解决了
查看>>
MySQL底层概述—1.InnoDB内存结构
查看>>
MySQL底层概述—2.InnoDB磁盘结构
查看>>
MySQL底层概述—3.InnoDB线程模型
查看>>
MySQL底层概述—4.InnoDB数据文件
查看>>
MySQL底层概述—5.InnoDB参数优化
查看>>
MySQL底层概述—6.索引原理
查看>>
MySQL底层概述—7.优化原则及慢查询
查看>>
MySQL底层概述—8.JOIN排序索引优化
查看>>
MySQL底层概述—9.ACID与事务
查看>>
Mysql建立中英文全文索引(mysql5.7以上)
查看>>
mysql建立索引的几大原则
查看>>
Mysql建表中的 “FEDERATED 引擎连接失败 - Server Name Doesn‘t Exist“ 解决方法
查看>>
mysql开启bin-log日志,用于canal同步
查看>>