假设我们有一个分数列表,其中每个分数都是代表数字(分子/分母)的单独列表[分子,分母]。我们必须找到总和为1的分数对的数量。
因此,如果输入像分数= [[2,7],[3,12],[4,14],[5,7],[3,4],[1,4]],则输出将为4,因为(2/7 + 5/7),(3/12 + 3/4),(3/4 + 1/4),(4/14 + 5/7)是四个对的和到1。
为了解决这个问题,我们将按照以下步骤操作:
d:=新map
回答:= 0
对于分数中的每个分数i
ans:= ans + d [temp_x,temp_y]
x:= i [分子]
y:= i [分母]
g:=(x,y)的gcd
x:= x / g
y:= y / g
temp_x:= y-x
temp_y:= y
如果(temp_x,temp_y)在d中,则
d [x,y]:= 1 +(d [(x,y)]可用,否则为0)
返回ans
让我们看下面的实现以更好地理解:
class Solution: def solve(self, fractions): import math d = {} ans = 0 for i in fractions: x = i[0] y = i[1] g = math.gcd(x, y) x /= g y /= g temp_x = y - x temp_y = y if (temp_x, temp_y) in d: ans += d[(temp_x, temp_y)] d[(x, y)] = d.get((x, y), 0) + 1 return ans ob = Solution()fractions = [[2, 7],[3, 12],[4, 14],[5, 7],[3, 4],[1, 4]] print(ob.solve(fractions))
[[2, 7],[3, 12],[4, 14],[5, 7],[3, 4],[1, 4]]
输出结果
4