Skip to content

Commit 78c0109

Browse files
Add files via upload
1 parent 93a9c28 commit 78c0109

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// 第一种方式 线性的时间复杂度 手动维度若干个变量来记录最大值和最小值
2+
// Runtime: 48 ms, faster than 81.12% of C++ online submissions for Maximum Product of Three Numbers.
3+
// Memory Usage: 10.9 MB, less than 86.67% of C++ online submissions for Maximum Product of Three Numbers.
4+
5+
class Solution
6+
{
7+
public:
8+
int maximumProduct(vector<int>& nums)
9+
{
10+
int max1 = INT_MIN;
11+
int max2 = INT_MIN;
12+
int max3 = INT_MIN;
13+
14+
int min1 = INT_MAX;
15+
int min2 = INT_MAX;
16+
17+
for (auto num : nums)
18+
{
19+
// 手动更新三个最大值
20+
if (num >= max1)
21+
{
22+
max3 = max2;
23+
max2 = max1;
24+
max1 = num;
25+
}
26+
else if (num >= max2)
27+
{
28+
max3 = max2;
29+
max2 = num;
30+
}
31+
else if (num > max3)
32+
max3 = num;
33+
34+
// 手动更新两个最小值
35+
if (num <= min1)
36+
{
37+
min2 = min1;
38+
min1 = num;
39+
}
40+
else if (num < min2)
41+
min2 = num;
42+
}
43+
44+
int res1 = max1 * max2 * max3;
45+
int res2 = max1 * min1 * min2;
46+
return max(res1, res2);
47+
}
48+
};
49+
50+
51+
// 如果题目问最大的N个数相乘的话,手动维护变量就不太方便了,因此可以考虑使用最大堆和最小堆的方式
52+
// Runtime: 48 ms, faster than 81.12% of C++ online submissions for Maximum Product of Three Numbers.
53+
// Memory Usage: 11 MB, less than 66.67% of C++ online submissions for Maximum Product of Three Numbers.
54+
class Solution
55+
{
56+
public:
57+
int maximumProduct(vector<int>& nums)
58+
{
59+
// 初始化最小堆和最大堆
60+
vector<int> maxHeap;
61+
vector<int> minHeap;
62+
63+
for (int i = 0; i < 3; ++i)
64+
{
65+
maxHeap.push_back(nums[i]);
66+
minHeap.push_back(nums[i]);
67+
}
68+
69+
sort(maxHeap.begin(), maxHeap.end());
70+
maxHeap.pop_back();
71+
72+
auto great = [](const int& item1, const int& item2){return item1 > item2;};
73+
make_heap(minHeap.begin(), minHeap.end(), great);
74+
75+
// 循环插入
76+
for (int i = 3; i < nums.size(); ++i)
77+
{
78+
if (nums[i] < maxHeap[0])
79+
{
80+
pop_heap(maxHeap.begin(), maxHeap.end());
81+
maxHeap.pop_back();
82+
83+
maxHeap.push_back(nums[i]);
84+
push_heap(maxHeap.begin(), maxHeap.end());
85+
}
86+
87+
if (nums[i] > minHeap[0])
88+
{
89+
pop_heap(minHeap.begin(), minHeap.end(), great);
90+
minHeap.pop_back();
91+
92+
minHeap.push_back(nums[i]);
93+
push_heap(minHeap.begin(), minHeap.end(), great);
94+
}
95+
}
96+
97+
// 计算最终结果
98+
int res1 = minHeap[0] * minHeap[1] * minHeap[2];
99+
int res2 = max(minHeap[1], minHeap[2]) * maxHeap[0] * maxHeap[1];
100+
return max(res1, res2);
101+
}
102+
};

0 commit comments

Comments
 (0)