二分查找,但会超时,主要是数组中的相同元素过度而导致延申查找超时(时间复杂度变成O(N^2),原本应为O(NlogN))
class Solution {
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
vector<int> res;
const int m = potions.size();
sort(potions.begin(), potions.end());
for (int i = 0; i < spells.size(); i++) {
double target = static_cast<double>(success) / spells[i];
int tmp = binary_search(target, potions, m);
res.emplace_back(tmp);
}
return res;
}
int binary_search(double& target, vector<int>& potions, const int& m) {
if (m == 1) {
return potions[0] < target ? 0 : 1;
}
int left = 0;
int right = m - 1;
int mid = left + (right - left) / 2;
while (left < right) {
if (left < right - 1) {
if (potions[mid] < target) {
left = mid;
} else if (potions[mid] > target) {
right = mid;
} else { //能找到target值
int tmp = m - mid;
int curr_left = mid;
while (curr_left-1 >= 0 && potions[curr_left-1] == target) {
curr_left--;
tmp++;
}
return tmp;
}
} else {
if (potions[left] >= target) {
return m - left;
} else if (potions[right] >= target && potions[left] < target) {
return m - right;
} else {
return 0;
}
}
mid = left + (right - left) / 2;
}
return 0;
}
};