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

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.