前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 1885. Count Pairs in Two Arrays(二分查找)

LeetCode 1885. Count Pairs in Two Arrays(二分查找)

作者头像
Michael阿明
发布2021-09-06 11:43:42
3450
发布2021-09-06 11:43:42
举报
文章被收录于专栏:Michael阿明学习之路

文章目录

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.

代码语言:javascript
复制
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. 解题

  • 先进行不等式变换,−nums2[i]>nums2[j]−nums1[j], 两数组做差得到 diff 数组diff[i]+diff[j]>0,diff 数组排序,对每个 diff[i],查找 另一个的下限,计算有多少数满足
代码语言:javascript
复制
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!=j
        int 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,减 1
                ans--;
        }
        return ans/2; // i < j 有一半是重复的
    }
};

228 ms 92.8 MB C++


我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/08/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档