forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp
- Loading branch information
1 parent
25c3e9f
commit c5aeb89
Showing
1 changed file
with
75 additions
and
0 deletions.
There are no files selected for viewing
75 changes: 75 additions & 0 deletions
75
...allest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
using LL = long long; | ||
class Solution { | ||
public: | ||
long long kthSmallestProduct(vector<int>& nums1, vector<int>& 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<int>& nums1, vector<int>& nums2) | ||
{ | ||
LL ret = 0; | ||
|
||
if (mid >= 0) | ||
{ | ||
int j0 = nums2.size()-1; | ||
int j1 = nums2.size()-1; | ||
|
||
for (int i=0; i<nums1.size(); i++) | ||
{ | ||
if (nums1[i]>0) | ||
{ | ||
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; i<nums1.size(); i++) | ||
{ | ||
if (nums1[i]>0) | ||
{ | ||
while (j0<nums2.size() && (LL)nums1[i]*(LL)nums2[j0] <= mid) | ||
j0++; | ||
ret += j0; | ||
} | ||
else if (nums1[i]==0) | ||
ret += 0; | ||
else | ||
{ | ||
while (j1<nums2.size() && (LL)nums1[i]*(LL)nums2[j1] > mid) | ||
j1++; | ||
ret += nums2.size()-j1; | ||
} | ||
} | ||
} | ||
|
||
return ret; | ||
} | ||
}; |