From fd483ee6a4b4c020a94f79e202296f0cb8a0fb4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Tue, 11 Sep 2018 21:18:53 +0800 Subject: [PATCH] Create 628. Maximum Product of Three Numbers.md --- 628. Maximum Product of Three Numbers.md | 38 ++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 628. Maximum Product of Three Numbers.md diff --git a/628. Maximum Product of Three Numbers.md b/628. Maximum Product of Three Numbers.md new file mode 100644 index 0000000..46a75a8 --- /dev/null +++ b/628. Maximum Product of Three Numbers.md @@ -0,0 +1,38 @@ +# [628. Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/description/) +# 思路 +这题由于可能存在负数和0,所以当数组元素个数大于3时需要分情况仔细考虑: +* (1. 全是非正数,则选三个最大的数相乘即可; +* (2. 只有一个正数,用这个(最大的)正数乘以最小的两个数(肯定是非正数)即可; +* (3. 有2个正数,选最大的(正)数与最小的两个(非正)数相乘; +* (4. 有3个及以上的正数,选三个最大的数相乘。 + +综上,这三个数要么是三个最大的数(1、4),要么是一个最大的数与两个最小的数(2、3)。 +所以找出最大的三个数与最小的两个数,然后再比较两种乘积的大小即可。 +时间复杂度O(n) +# C++ +``` +class Solution { +public: + int maximumProduct(vector& nums) { + // if(nums.size() == 3) return nums[0] * nums[1] * nums[2]; + int mx1 = INT_MIN, mx2 = INT_MIN, mx3 = INT_MIN; + int mn1 = INT_MAX, mn2 = INT_MAX; + for (int num : nums) { // 注意这种用一次循环求最大三个数的方式 + if (num > mx1) { + mx3 = mx2; mx2 = mx1; mx1 = num; + } else if (num > mx2) { + mx3 = mx2; mx2 = num; + } else if (num > mx3) { + mx3 = num; + } + + if (num < mn1) { + mn2 = mn1; mn1 = num; + } else if (num < mn2) { + mn2 = num; + } + } + return max(mx1 * mx2 * mx3, mx1 * mn1 * mn2); + } +}; +```