-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path2040. Kth Smallest Product of Two Sorted Arrays.java
More file actions
44 lines (39 loc) · 1.28 KB
/
2040. Kth Smallest Product of Two Sorted Arrays.java
File metadata and controls
44 lines (39 loc) · 1.28 KB
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
//donot edit this code
class Solution {
public long kthSmallestProduct(int[] nums1, int[] nums2, long k) {
long left = -10000000000L;
long right = 10000000000L;
while (left < right) {
long mid = left + (right - left) / 2;
if (countProducts(nums1, nums2, mid) < k) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
private long countProducts(int[] nums1, int[] nums2, long target) {
long count = 0;
for (int num1 : nums1) {
if (num1 == 0) {
if (target >= 0) count += nums2.length;
continue;
}
int low = 0, high = nums2.length;
while (low < high) {
int mid = low + (high - low) / 2;
long product = (long) num1 * nums2[mid];
if (product <= target) {
if (num1 > 0) low = mid + 1;
else high = mid;
} else {
if (num1 > 0) high = mid;
else low = mid + 1;
}
}
count += (num1 > 0) ? low : nums2.length - low;
}
return count;
}
}