Leetcode 365. Water and Jug Problem

举报
xindoo 发表于 2022/04/16 00:13:48 2022/04/16
【摘要】 Water and Jug Problem You are given two jugs with capacities x and y litres. There is an infinit...

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;
    }
}

文章来源: xindoo.blog.csdn.net,作者:xindoo,版权归原作者所有,如需转载,请联系作者。

原文链接:xindoo.blog.csdn.net/article/details/61206546

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。