628. Maximum Product of Three Numbers
来源:互联网 发布:文言中乎的用法和意义 编辑:程序博客网 时间:2024/05/13 17:56
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]Output: 6
Example 2:
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.
Seen this question in a real interview before?
O(n):
public class Solution { public int maximumProduct(int[] nums) { int l1 = Integer.MAX_VALUE;int l2 = Integer.MAX_VALUE;int f1 = Integer.MIN_VALUE;int f2 = Integer.MIN_VALUE;int f3 = Integer.MIN_VALUE;for (int i : nums) {if (i > f1) {f3 = f2;f2 = f1;f1 = i;} else if (i > f2) {f3 = f2;f2 = i;} else if (i > f3)f3 = i;if (i < l1) {l2 = l1;l1 = i;} else if (i < l2)l2 = i;}return Math.max(f1 * f2 * f3, f1 * l1 * l2); }}
O(nlogn):
public class Solution { public int maximumProduct(int[] nums) { Arrays.sort(nums);int n = nums.length;int a = nums[0] * nums[1] * nums[n - 1];int b = nums[n - 1] * nums[n - 2] * nums[n - 3];return Math.max(a, b); }}
阅读全文
0 0
- [leetcode]628. Maximum Product of Three Numbers
- leetcode#628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- leetcode: 628. Maximum Product of Three Numbers
- leetcode 628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- [LeetCode] 628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- [leetcode]628. Maximum Product of Three Numbers
- LeetCode 628. Maximum Product of Three Numbers
- leetcode -- 628. Maximum Product of Three Numbers
- [LeetCode]628. Maximum Product of Three Numbers
- [LeetCode]628. Maximum Product of Three Numbers
- poj 1236 Network of Schools (tarjan)
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 动态绑定 vs 静态绑定
- Android--ListView实现所有Item的全选和未选
- 如何处理在下载文件时,中文的文件名传输
- 628. Maximum Product of Three Numbers
- intellij idean 打jar包
- poj2785(二分折半枚举)
- 回文链表的判断
- BZOJ 1455 可并堆(左偏树) 解题报告
- Ubuntu下的Eclipse和JDK的安装
- Linux 目录处理命令
- C语言之指针数组和数组指针
- iOS 日常开发后我们可以补充这些知识