1726. 同积元组

给你一个由 不同 正整数组成的数组 nums ,请你返回满足 a * b = c * d 的元组 (a, b, c, d) 的数量。其中 a、b、c 和 d 都是 nums 中的元素,且 a != b != c != d 。


复杂度:O(N*N)

思路:用HashMap记录乘积相同的组数n。ans = ans+n*(n-1)*4

class Solution {
    public int tupleSameProduct(int[] nums) {
      int ans = 0;
      Map<Integer, Integer> map = new HashMap();
      int n = nums.length;
      for(int i=0; i<n; i++) {
        for(int j= i+1; j<n; j++ ) {
          int tmp = nums[i]*nums[j];
          map.put(tmp, map.getOrDefault(tmp, 0)+1);
        }
      }
      for(Map.Entry<Integer, Integer> entry:map.entrySet()){
          int num = entry.getValue();
          ans = ans + num*(num-1)*4;     
      }
      return ans;
    }
}

你可能感兴趣的:(java,算法,数据结构)