边工作边刷题:70天一遍leetcode: day 41-2
Water and Jug Problem
要点:利用了Bézout’s theorem:mx+n*y对于任意m,n都是gcd(x,y)的整倍数。所以z是gcd整倍数并且z<=x+y
- gcd(a,b):a一定<b做辗转相除。结束条件是a=0,返回b(和1没关系)。而gcd==0只可能a=b=0
class Solution(object):
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
def gcd(a, b): # assume a<b
if a==0: return b # error 1: return b not return 0
return gcd(b%a, a)
if x>y: x,y=y,x
gval = gcd(x,y)
#print gval
if gval==0:
return z==0
return z%gval==0 and z<=x+y
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步