生活随笔
收集整理的這篇文章主要介紹了
三个数的最大乘积
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給定一個整型數(shù)組,在數(shù)組中找出由三個數(shù)組成的最大乘積,并輸出這個乘積。
輸入
: [1,2,3]
輸出
: 6
輸入: [1,2,3,4]
輸出: 24
給定的整型數(shù)組長度范圍是[3,104],數(shù)組中所有的元素范圍是[-1000, 1000]。
輸入的數(shù)組中任意三個數(shù)的乘積不會超出32位有符號整數(shù)的范圍。
class Solution
{
public
:void quickSort(vector
<int>& nums
, int low
, int high
) {if (high
<= low
) {return;}int key
= nums
[low
];int i
= low
;int j
= high
+1;while(true
) {while(nums
[++i
] < key
) {if (i
== high
) {break;}}while(nums
[--j
] > key
) {if (j
== low
) {break;}}if (i
>=j
) {break;}int temp
= nums
[i
];nums
[i
] = nums
[j
];nums
[j
] = temp
;}nums
[low
] = nums
[j
];nums
[j
] = key
;quickSort(nums
, low
, j
-1);quickSort(nums
, j
+1, high
);}int maximumProduct(vector
<int>& nums
) {quickSort(nums
, 0, nums
.size()-1);return max(nums
[nums
.size()-1] * nums
[nums
.size()-2] * nums
[nums
.size()-3], nums
[nums
.size()-1] * nums
[0] * nums
[1]);}
};
class Solution
{
public
:int maximumProduct(vector
<int>& nums
) {int min1
= INT_MAX
, min2
= INT_MAX
;int max1
= INT_MIN
, max2
= INT_MIN
, max3
= INT_MIN
;for (const auto& num
: nums
) {if (num
< min1
) {min2
= min1
;min1
= num
;} else if (num
< min2
) {min2
= num
;}if (num
> max1
) {max3
= max2
;max2
= max1
;max1
= num
;} else if (num
> max2
) {max3
= max2
;max2
= num
;} else if (num
> max3
){max3
= num
;}}return max(max1
* max2
* max3
, max1
* min1
* min2
);}
};
來源:力扣(LeetCode)
總結(jié)
以上是生活随笔為你收集整理的三个数的最大乘积的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。