怎么销售网站建设,中国做外贸的网站有哪些内容,别人的抖音网站是怎么做的,中国十大网络科技公司力扣#xff08;LeetCode#xff09;官网 - 全球极客挚爱的技术成长平台备战技术面试#xff1f;力扣提供海量技术面试资源#xff0c;帮助你高效提升编程技能#xff0c;轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/tuple-with-same-product/
给你…力扣LeetCode官网 - 全球极客挚爱的技术成长平台备战技术面试力扣提供海量技术面试资源帮助你高效提升编程技能轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/tuple-with-same-product/
给你一个由 不同 正整数组成的数组 nums 请你返回满足 a * b c * d 的元组 (a, b, c, d) 的数量。其中 a、b、c 和 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 FourTupleObject {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]的乘积将其当做keyvalue为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);}}
如果value2的话就证明存在有乘积相等的元组。
因为这段代码超时了这里我发现value与乘积相等元组个数之间的关系例如value3则有213个符合条件的元组便使用了if语句判断value2利用以下式子计算元组个数
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.EntryInteger, Integer entry : hashMap.entrySet()) {res cal(entry.getValue());}return res;
}力扣官方题解
力扣LeetCode官网 - 全球极客挚爱的技术成长平台备战技术面试力扣提供海量技术面试资源帮助你高效提升编程技能轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/tuple-with-same-product/solutions/2470655/tong-ji-yuan-zu-by-leetcode-solution-7yyy/应该是3 * (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;HashMapInteger, 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;}
}