package
0.0.0-20241220224003-b7cf03a90b2b
Repository: https://github.com/szhou12/leetcode-go.git
Documentation: pkg.go.dev
# README
2040. Kth Smallest Product of Two Sorted Arrays
Solution idea
Binary Search 猜答案
Key: input array中有负数,所以matrix中的product可正可负,所以此时需要分类讨论:
Given nums1[i]
, find j
s.t. nums1[i] * nums2[j] <= mid
in order to find # of products less than or equal to mid
- Case 1: if
nums1[i] > 0
, thennums2[j] <= mid / nums1[i]
. Sincenums2
sorted in decreasing-order,j
should point to the last element<= mid / nums1[i]
. Thus,0...j
all satisfy the requirement. # of products less than or equal tomid
=j-0+1
.- Note 1: How to find
j
? Binary search onnums2
with target valuemid / nums1[i]
- Use
upperBound()
method to find the first indexk
s.t.nums2[k] > target
. Thus,j=k-1
- Use
- Note 2: It may NOT the case that
nums1[i] | mid
. Thus, takeFloor(mid / nums1[i])
- Note 1: How to find
- Case 2: if
nums1[i] = 0
, then0 * nums2[j] <= mid
- Case 2.1: if
mid < 0
, then noj
can work. # of products less than or equal tomid
= 0 - Case 2.2: if
mid >= 0
, then allj
will work. # of products less than or equal tomid
=len(nums2)
- Case 2.1: if
- Case 3: if
nums1[i] < 0
, thennums2[j] >= mid / nums1[i]
. Sincenums2
sorted in decreasing-order,j
should point to the first element>= mid / nums1[i]
. Thus,j...n-1
all satisfy the requirement. # of products less than or equal tomid
=n-1-j+1
.- Note 1: How to find
j
? Binary search onnums2
with target valuemid / nums1[i]
- Use
lowerBound()
method to find the first indexk
s.t.nums2[k] >= target
. Thus,j=k
- Note 2: It may NOT the case that
nums1[i] | mid
. Thus, takeCeil(mid / nums1[i])
- Use
- Note 1: How to find
Time complexity = $O(\log n * (n \log n)) = O(n\log n)$
Resource
【每日一题】LeetCode 2040. Kth Smallest Product of Two Sorted Arrays, 10/28/2021