Leetcode 365. Water and Jug Problem

Water and Jug Problem

You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.

If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.

  一句话理解题意:有容积为x和y升的俩水壶,能不能量出z升的水。
  我刚开始看到这题,立马就想了下暴力搜索的可能性,但考虑了下数据大小,立马放弃这个暴力的想法,于是意识到肯定有比较简单的数学方法,其实我自己没想到,后来看还是看了别人的代码,很多博客都直接给出了解法, 但没介绍为什么能这么解。所以我决定解释下我自己的思路。
  首先可以肯定的是只有xy俩水壶,大于x+y的水肯定是量不出来的,这个没啥大问题。重点是为什么只要x和y的最大公约数能整除z就可以量出z呢? 这里我只找到了一个裴蜀定理 来解释了。

public class Solution {
    private int gcd(int x, int y) {
        if (x%y == 0)
            return y;
        return gcd(y, x%y);
    }
    public boolean canMeasureWater(int x, int y, int z) {
        if (x+y < z)
            return false;
        if (x == 0 || y == 0)
            return x == z || y == z;
        int a = gcd(x, y);
        return z%a == 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xindoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值