【Leetcode】【中等】1726.同积元组

编程入门 行业动态 更新时间:2024-10-14 14:15:59

【<a href=https://www.elefans.com/category/jswz/34/1769930.html style=Leetcode】【中等】1726.同积元组"/>

【Leetcode】【中等】1726.同积元组

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。/

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

示例 1:

输入:nums = [2,3,4,6]
输出:8
解释:存在 8 个满足题意的元组:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)

示例 2:

输入:nums = [1,2,4,5,10]
输出:16
解释:存在 16 个满足题意的元组:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)

自己的思路

一开始真的去定义了一个四元组,做完超时了,后面改成HashMap,这里把四元组的代码贴出来,当做复习了。。。

public static class FourTuple<Object> {public Object first;public Object second;public Object third;public Object fourth;public FourTuple() {}public FourTuple(Object first, Object second, Object third, Object fourth) {this.first = first;this.second = second;this.third = third;this.fourth = fourth;}@Overridepublic String toString() {return "[" + this.first + "," + this.second + "," + this.third + "," + this.fourth + "]";}}

比较正确的思路

使用两层循环遍历数组nums,计算nums[i]与nums[j]的乘积,将其当做key,value为key出现的次数。如果原来没有这个key的,就放入1;如果原来有这个key的,就在它的基础上加1。

这段代码如下:

        for (int i = 0; i < len; i++) {int mul_result;for (int j = i + 1; j < len; j++) {mul_result = nums[i] * nums[j];hashMap.put(mul_result, hashMap.getOrDefault(mul_result, 0) + 1);}}

如果value>=2的话,就证明存在有乘积相等的元组。

因为这段代码超时了,这里我发现"value与乘积相等元组个数之间"的关系,例如value=3,则有2+1=3个符合条件的元组,便使用了if语句判断value>=2,利用以下式子计算元组个数:

public static int cal(int x) {int sum = 0;x = x - 1;while (x >= 1) {sum += x;x--;}return sum;
}public static int tupleSameProduct(int[] nums) {...int res = 0;for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {res += cal(entry.getValue());}return res;
}

力扣官方题解 

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。 * (3 - 1) / 2 = 3,而不是2 + 1 = 3。前者时间复杂为O(1),后者需要遍历,时间复杂度为O(n)。一个元组有8种不一样的排序,如下所示

(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)

所以每个元组就有n * (n - 1) / 2 * 8 = n * (n - 1) * 4。

代码

class Solution {public int tupleSameProduct(int[] nums) {int len = nums.length;HashMap<Integer, Integer> hashMap = new HashMap<>();int res = 0;for (int i = 0; i < len; i++) {int mul_result;for (int j = i + 1; j < len; j++) {mul_result = nums[i] * nums[j];hashMap.put(mul_result, hashMap.getOrDefault(mul_result, 0) + 1);}}for (Integer v : hashMap.values()) {res += v * (v - 1) * 4;}return res;}
}

更多推荐

【Leetcode】【中等】1726.同积元组

本文发布于:2023-12-04 06:49:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1660083.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Leetcode   积元组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!