From c5aeb890e61d0d39a87915e7aecde6d9e85e7ca4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 23:39:12 -0700 Subject: [PATCH] Create 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp --- ...allest-Product-of-Two-Sorted-Arrays_v2.cpp | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp diff --git a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp new file mode 100644 index 000000000..4c8a0186e --- /dev/null +++ b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp @@ -0,0 +1,75 @@ +using LL = long long; +class Solution { +public: + long long kthSmallestProduct(vector& nums1, vector& nums2, long long k) + { + if (nums1.size() > nums2.size()) + return kthSmallestProduct(nums2, nums1, k); + + LL left = -1e10, right = 1e10; + while (left < right) + { + LL mid = left+(right-left)/2; + LL count = countSmallerOrEqual(mid, nums1, nums2); + if (count < k) + left = mid+1; + else + right = mid; + } + return left; + } + + LL countSmallerOrEqual(LL mid, vector& nums1, vector& nums2) + { + LL ret = 0; + + if (mid >= 0) + { + int j0 = nums2.size()-1; + int j1 = nums2.size()-1; + + for (int i=0; i0) + { + while (j0>=0 && (LL)nums1[i]*(LL)nums2[j0] > mid) + j0--; + ret += j0+1; + } + else if (nums1[i]==0) + ret += nums2.size(); + else + { + while (j1>=0 && (LL)nums1[i]*(LL)nums2[j1] <= mid) + j1--; + ret += nums2.size()-1-j1; + } + } + } + else + { + int j0 = 0; + int j1 = 0; + + for (int i=0; i0) + { + while (j0 mid) + j1++; + ret += nums2.size()-j1; + } + } + } + + return ret; + } +};