class Solution {
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
sort(potions.begin(), potions.end());
vector<int> ans;
int m = potions.size();
for (int& v : spells) {
int i = lower_bound(potions.begin(), potions.end(), success * 1.0 / v) - potions.begin();
ans.push_back(m - i);
}
return ans;
}
};
作者:ylb
class Solution {
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
sort(potions.begin(), potions.end());
vector<int> ans;
int m = potions.size();
for (int& v : spells) {
double p = success * 1.0 / v ;
int i = lower_bound(potions.begin(), potions.end(), p) - potions.begin();
ans.push_back(m - i);
}
return ans;
}
};
如果将double 转为long long, 会损失精度。
在C++中,lower_bound
和upper_bound
函数都用于在有序序列中进行二分查找。它们的区别在于:
lower_bound
函数返回的是第一个大于或等于给定值的元素的位置。upper_bound
函数返回的是第一个大于给定值的元素的位置。class Solution {
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
sort(potions.begin(), potions.end());
vector<int> res;
for (auto& i : spells) {
long long t = (success + i - 1) / i - 1;
res.push_back(potions.size() - (upper_bound(potions.begin(), potions.end(), t) - potions.begin()));
}
return res;
}
};
作者:力扣官方题解
sucess = 17 i=8, (success + i - 1) / i - 1 =2, 17/8 =2
sucess = 16 i=8, (success + i - 1) / i - 1 =1, 16/8 =2
sucess = 15 i=8, (success + i - 1) / i - 1 =1, 15/8 =1
所以使用upper_bound, 可以得到符合预期的范围。
下面是一个使用lower_bound
和upper_bound
函数的示例:
#include
#include
#include
int main() {
std::vector<int> vec = {10, 20, 30, 30, 40, 50};
// 使用 lower_bound 查找第一个大于或等于 30 的元素的位置
std::vector<int>::iterator lower = std::lower_bound(vec.begin(), vec.end(), 30);
// 使用 upper_bound 查找第一个大于 30 的元素的位置
std::vector<int>::iterator upper = std::upper_bound(vec.begin(), vec.end(), 30);
if (lower != vec.end()) {
std::cout << "第一个大于或等于 30 的元素的位置是: " << std::distance(vec.begin(), lower) << std::endl;
} else {
std::cout << "没有找到大于或等于 30 的元素" << std::endl;
}
if (upper != vec.end()) {
std::cout << "第一个大于 30 的元素的位置是: " << std::distance(vec.begin(), upper) << std::endl;
} else {
std::cout << "没有找到大于 30 的元素" << std::endl;
}
return 0;
}
在这个示例中,我们创建了一个包含整数的vector,并使用lower_bound
函数和upper_bound
函数在vector中查找符合条件的元素的位置。如果找到了这样的元素,我们将输出它的位置;否则,我们将输出没有找到的消息。