628. Maximum Product of Three Numbers(Java)
来源:互联网 发布:广电网络的wifi网址 编辑:程序博客网 时间:2024/06/15 13:53
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:
1、The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].2、Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
代码1:先排序,时间复杂度O(nlogn) ,空间复杂度O(1)
class Solution { public int maximumProduct(int[] nums) { Arrays.sort(nums); int len = nums.length; return Math.max(nums[len - 1] * nums[len - 2] * nums[len - 3], nums[0] * nums[1] * nums[len - 1]); }}
代码2:时间复杂度O(n),空间复杂度O(1)
class Solution { public int maximumProduct(int[] nums) { int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE, min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; for (int n : nums) { if (n > max1) { max3 = max2; max2 = max1; max1 = n; } else if (n > max2) { max3 = max2; max2 = n; } else if (n > max3) max3 = n; } for (int n : nums) { if (n < min1) { min2 = min1; min1 = n; } else if (n < min2) min2 = n; } return Math.max(max1 * max2 * max3, max1 * min1 * min2); }}
阅读全文
0 0
- 628. Maximum Product of Three Numbers(Java)
- LeetCode-628. Maximum Product of Three Numbers (Java)
- [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
- 软件测试常问题目
- 最长公共子序列LCS简介
- Head First Java 总结(二)
- 七牛云私有空间指定目录大量文件压缩示例
- LeetCode
- 628. Maximum Product of Three Numbers(Java)
- JavaScript简介
- MyBatis的缓存机制
- 第二周java作业--2017.09.06
- 区间dp总结
- 数据对齐问题
- Java中的hashset
- 周辉:《产品研发管理》——学习/消化/吸收
- Mpi与Cuda混合编程(Makefile)