文章目录
- 1. 题目
- 2. 解题
1. 题目
Given two integer arrays nums1 and nums2 of length n, count the pairs of indices (i, j) such that i < j
and nums1[i] + nums1[j] > nums2[i] + nums2[j]
.
Return the number of pairs satisfying the condition.
Example 1:
Input: nums1 = [2,1,2,1], nums2 = [1,2,1,2]
Output: 1
Explanation: The pairs satisfying the condition are:
- (0, 2) where 2 + 2 > 1 + 1.Example 2:
Input: nums1 = [1,10,6,2], nums2 = [1,4,1,5]
Output: 5
Explanation: The pairs satisfying the condition are:
- (0, 1) where 1 + 10 > 1 + 4.
- (0, 2) where 1 + 6 > 1 + 1.
- (1, 2) where 10 + 6 > 4 + 1.
- (1, 3) where 10 + 2 > 4 + 5.
- (2, 3) where 6 + 2 > 1 + 5.Constraints:
n == nums1.length == nums2.length
1 <= n <= 10^5
1 <= nums1[i], nums2[i] <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-pairs-in-two-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 先进行不等式变换,nums1[i]−nums2[i]>nums2[j]−nums1[j]nums1[i]-nums2[i] > nums2[j]-nums1[j]nums1[i]−nums2[i]>nums2[j]−nums1[j], 两数组做差得到
diff
数组 - diff[i]+diff[j]>0diff[i] + diff[j] > 0diff[i]+diff[j]>0,
diff
数组排序,对每个diff[i]
,查找 另一个的下限,计算有多少数满足
class Solution {
public:long long countPairs(vector<int>& nums1, vector<int>& nums2) {// 等价于 nums1[i]-nums2[i] > nums2[j]-nums1[j], i < j// diff[i] + diff[j] > 0, i,j顺序调换也可以满足,所以只需 i!=jint n = nums1.size();vector<int> diff(n);for(int i = 0; i < n; ++i)diff[i] = nums1[i] - nums2[i];sort(diff.begin(), diff.end());long long ans = 0;for(int i = 0; i < n; ++i){auto it = lower_bound(diff.begin(), diff.end(), -diff[i]+1);ans += diff.end()-it;//这么多数满足if(it <= diff.begin()+i)//包含了i,减 1ans--;}return ans/2; // i < j 有一半是重复的}
};
228 ms 92.8 MB C++
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!