-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_2300_successfulPairs.cc
65 lines (63 loc) · 1.53 KB
/
Problem_2300_successfulPairs.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success)
{
int n = spells.size();
int m = potions.size();
vector<int> idx(n);
for (int i = 0; i < n; i++)
{
idx[i] = i;
}
// 根据咒语强度从小到大排序
std::sort(idx.begin(), idx.end(), [&](int i, int j) { return spells[i] < spells[j]; });
std::sort(potions.begin(), potions.end());
vector<int> pairs(n);
int left = 0;
int right = n - 1;
int mid = 0;
while (left <= right)
{
mid = left + (right - left) / 2;
// 如果 咒语强度 * 药水最大强度 < 成功阈值的话,说明这个咒语永远达不到要求
if ((long long) spells[idx[mid]] * potions[m - 1] < success)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
for (int i = 0; i < left; i++)
{
// 小于这个强度的咒语都是达不到要求的
pairs[idx[i]] = 0;
}
for (int i = left; i < n; i++)
{
left = 0;
right = m - 1;
while (left <= right)
{
mid = left + (right - left) / 2;
// 找到药水强度的阈值,>= 这个阈值的药水都符合
if ((long long) spells[idx[i]] * potions[mid] < success)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
pairs[idx[i]] = m - left;
}
return pairs;
}
};