Re: [閒聊] 每日leetcode
題目
給一個裡面有很多不同數字的陣列
我們要找裡面有幾組tuple {a,b,c,d}符合a!=b!=c!=d且ab=cd
思路
先去算nums裡面數字兩兩相乘乘積出現的頻率塞進一個字典
假設一個乘積出現n次
我們要取2組出來排列就有C(n,2)× 2!種可能
阿兩組裡面ab可以互換cd也可以互換所以組數要再× 4
總共就是C(n,2)× 8=4n(n-1)組
遍歷字典每一項加起來就是答案了
Code:
class Solution(object):
def tupleSameProduct(self, nums):
dict={}
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
product=nums[i]*nums[j]
if product in dict:
dict[product]+=1
else:
dict[product]=1
ans=0
for i in dict:
ans+=4*(dict[i]-1)*dict[i]
return ans
我變數名稱都取超爛
嗚哇哇阿阿
--
https://i.imgur.com/P179G56.jpeg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.237.4.29 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1738810272.A.161.html
※ 編輯: Meaverzt (36.237.4.29 臺灣), 02/06/2025 10:54:28
討論串 (同標題文章)
完整討論串 (本文為第 1324 之 1552 篇):