前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 365. Water and Jug Problem

Leetcode 365. Water and Jug Problem

作者头像
xindoo
发布2021-01-22 11:43:26
2850
发布2021-01-22 11:43:26
举报
文章被收录于专栏:XINDOO的专栏XINDOO的专栏

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呢? 这里我只找到了一个裴蜀定理 来解释了。

代码语言:javascript
复制
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;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-03-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档