1. 程式人生 > 實用技巧 >【leetcode】1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers

【leetcode】1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers

題目如下:

Given two arrays of integersnums1andnums2, return the number of triplets formed (type 1 and type 2) under the following rules:

  • Type 1: Triplet (i, j, k)ifnums1[i]2== nums2[j] * nums2[k]where0 <= i < nums1.lengthand0 <= j < k < nums2.length.
  • Type 2:Triplet (i, j, k) ifnums2[i]2== nums1[j] * nums1[k]
    where0 <= i < nums2.lengthand0 <= j < k < nums1.length.

Example 1:

Input: nums1 = [7,4], nums2 = [5,2,8,9]
Output: 1
Explanation: Type 1: (1,1,2), nums1[1]^2 = nums2[1] * nums2[2]. (4^2 = 2 * 8). 

Example 2:

Input: nums1 = [1,1], nums2 = [1,1,1]
Output: 9
Explanation: All Triplets are valid, because 1^2 = 1 * 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2).  nums1[i]^2 = nums2[j] * nums2[k].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]^2 = nums1[j] * nums1[k].

Example 3:

Input: nums1 = [7,7,8,3], nums2 = [1,2,9,7]
Output: 2
Explanation: There are 2 valid triplets.
Type 1: (3,0,2).  nums1[3]^2 = nums2[0] * nums2[2].
Type 2: (3,0,1).  nums2[3]^2 = nums1[0] * nums1[1].

Example 4:

Input: nums1 = [4,7,9,11,23], nums2 = [3,5,1024,12,18]
Output: 0
Explanation: There are no valid triplets.

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 1 <= nums1[i], nums2[i] <= 10^5

解題思路:題目很簡單,先分別把nums1和nums2中任意兩個下標不一致的元素的乘積算出來,統計出每個元素出現的次數,然後再計算對應的陣列中這個元素作為平方值出現的次數即可。

程式碼如下:

class Solution(object):
    def numTriplets(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: int
        """
        res = 0
        dic_num1 = {}
        dic_num2 = {}

        for i in range(len(nums1)):
            for j in range(i+1,len(nums1)):
                v = nums1[i] * nums1[j]
                dic_num1[v] = dic_num1.setdefault(v,0) + 1

        for i in range(len(nums2)):
            for j in range(i+1,len(nums2)):
                v = nums2[i] * nums2[j]
                dic_num2[v] = dic_num2.setdefault(v,0) + 1

        for i in nums1:
            res += dic_num2.get(i * i,0)
        for i in nums2:
            res += dic_num1.get(i * i, 0)

        return res