【哈希表】B000_LC_数的平方等于两数乘积的方法数(map预处理)

给你两个整数数组 nums1 和 nums2 ,请你返回根据以下规则形成的三元组的数目(类型 1 和类型 2 ):
类型 1:三元组 (i, j, k) ,如果 nums1[i]2 == nums2[j] * nums2[k] 其中 0 <= i < nums1.length 且 0 <= j < k < nums2.length
类型 2:三元组 (i, j, k) ,如果 nums2[i]2 == nums1[j] * nums1[k] 其中 0 <= i < nums2.length 且 0 <= j < k < nums1.length

输入:nums1 = [7,4], nums2 = [5,2,8,9]
输出:1
解释:类型 1:(1,1,2), nums1[1]^2 = nums2[1] * nums2[2] (4^2 = 2 * 8)

方法一:map预处理

不要嵌套循环遍历 map,那样会妥妥的O(n),用map内部的O(logn)查找去查找目标值更快

typedef long long ll;
class Solution {
public:
    int numTriplets(vector<int>& A, vector<int>& B) {
        ll n=A.size(), m=B.size(), ans=0;
        unordered_map<ll, ll> m1, m2;
        
        for (int i=0; i<n-1; i++)
        for (int j=i+1; j<n; j++) 
            m1[(ll) A[i]*A[j]]++;
        for (int i=0; i<m-1; i++)
        for (int j=i+1; j<m; j++) 
            m2[(ll) B[i]*B[j]]++;
        
        for (int i=0; i<n; i++) {
            ll t=(ll)A[i]*A[i];
            if (m2.find(t)!=m2.end()) ans+=m2[t];
        }
        for (int i=0; i<m; i++) {
            ll t=(ll)B[i]*B[i];
            if (m1.find(t)!=m1.end()) ans+=m1[t];
        }
        return ans;
    }
};

复杂度分析

  • Time\(O(n^2)\)
  • Space\(O(n)\)
posted @ 2020-09-06 17:36  童年の波鞋  阅读(136)  评论(0编辑  收藏  举报