LC.P2300[咒语和药水的成功对数]

方法一:排序+二分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] successfulPairs(int[] spells, int[] potions, long success) {
int n = spells.length, m = potions.length;
Arrays.sort(potions);
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
int left = 0, right = m - 1;
while (left < right) {
int mid = left + right >> 1;
if ((long) spells[i] * potions[mid] >= success) right = mid;
else left = mid + 1;
}
if ((long) spells[i] * potions[right] >= success) ans[i] = m - right;
}
return ans;
}
}
  • 时间复杂度:$O(mlogm + nlogm)$
  • 空间复杂度:$O(logm + n)$