Leetcode 1885 Count Pairs in Two Arrays
Kardel Chen
Posted on January 16, 2022
class Solution {
public long countPairs(int[] nums1, int[] nums2) {
// We are counting i&j that ((nums1[i]-nums2[i])+(nums1[j]-nums2[j])>0)
int N = nums1.length;
int[] nums = new int[N];
for (int i = 0; i < N; i++) {
nums[i] = nums1[i] - nums2[i];
}
// sort that, then this question is like a 2Sum question.
Arrays.sort(nums);
long res = 0;
// Use two pointers like 2Sum
int i = 0;
int j = nums.length - 1;
while(j > i){
// if nums[i] + nums[j] > 0, then (j-i) are all available results
if(nums[i] + nums[j] > 0){
res += j - i;
j--;
}else{
// or increase i to try new value to make the sum larger
i++;
}
}
return res;
}
}
💖 💪 🙅 🚩
Kardel Chen
Posted on January 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
githubcopilot AI Innovations at Microsoft Ignite 2024 What You Need to Know (Part 2)
November 29, 2024