3164. 优质数对的总数 II

其实和3162思路是一样的,只是3162的数据范围可以进行暴力而3164不可以

思路

将nums1[i]/(nums2[j] * k)所得的结果称为d,枚举d直到d * nums2[j] * k > nums1[i]

时间复杂度:O(n+m+k/v * logm)

Solutions
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
using ll = long long;
class Solution {
public:
long long numberOfPairs(vector<int>& nums1, vector<int>& nums2, int k) {
unordered_map<int, int> cnt, cnt2;
int mx = 0;
for (const auto& i : nums1) {
cnt[i]++;
mx = max(mx, i);
}
for (const auto& i : nums2) {
cnt2[i]++;
}
ll res = 0;
for (const auto& [x,y] : cnt2) {
int a = x, ct = y;
for (int b = a * k; b <= mx; b += a * k) {
if (cnt.count(b) > 0) {
res += 1L * cnt[b] * ct;
}
}
}
return res;
}
};