日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/7/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 1885. Count Pairs in Two Arrays(二分查找) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 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阿明),一起加油、一起學習進步!

總結

以上是生活随笔為你收集整理的LeetCode 1885. Count Pairs in Two Arrays(二分查找)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。