博客
关于我
线性扫描--求数组中三个数最大乘积
阅读量:329 次
发布时间: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/

你可能感兴趣的文章
纯客户端页面关键字搜索高亮jQuery插件
查看>>
Java温故而知新-反射机制
查看>>
eclipse引用sun.misc开头的类
查看>>
关于EFI系统分区(ESP)你应该知道的3件事
查看>>
Servlet2.5的增删改查功能分析与实现------删除功能(四)
查看>>
Session验证码的实现(2018-7-3)
查看>>
spring启动错误:Could not resolve placeholder
查看>>
选择性估算器绕过行安全策略漏洞
查看>>
对PostgreSQL数据库结构的宏观理解
查看>>
查询某表格上次进行vacuum的时间
查看>>
invalid byte sequence for encoding
查看>>
聊一聊那些应该了解的大佬(飞控,人工智能方向)
查看>>
redis向数组中添加值并查看数组长度
查看>>
JS编写一个函数,计算三个不同数字的大小,按从小到大顺序打印(穷举法)
查看>>
sqlplus的基本使用
查看>>
Oracle删除主表数据
查看>>
Oracle常用SQL
查看>>
技术美术面试问题整理
查看>>
C++学习记录 五、C++提高编程(2)
查看>>
4 Java 访问控制符号的范围
查看>>