leetcode:Water and Jug Problem

来源:互联网 发布:javascript特效实例 编辑:程序博客网 时间:2024/05/16 06:12

原题:

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.

Operations allowed:

Fill any of the jugs completely with water.

Empty any of the jugs.

Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.

Example1:

Input: x = 3, y = 5, z = 4Output: True


Example2:

Input: x = 2, y = 6, z = 5Output: False

分析:

题意为:给定两个容量分别为x,y的水壶容器,可以使用任意数量的水,通过往里倒水和往外倒水,或者两个水壶之间倒水,请判断能否用这两个水壶量出容量为z的水?

这是一道经典的智力题,如例子1中,我们可以先往3升的水壶倒满水,然后再将里面的水全部倒入5升的水壶,这样3升水壶水量为0,5升水壶水量为3升,在将3升水壶倒满,将

3升水壶的水全部倒入5升水壶,倒满为止,结果3升水壶水量为1,5升水壶水量为5升,再将5升水壶的水全部倒空,将3升水壶里的1升水倒入5升水壶,这样得到0升水的3升水

壶和1升水的5升水壶,再将3升水壶倒满,然后全部倒入5升水壶,就得到了想要的4升水,返回true。


我们要根据任意的x和y判断能否得到z.

首先可以排除特殊情况。如果x+y<z,即两个容器double装满水的容量和比z小,则无论如何也得不到,返回false;

如果z=0,任何情况的x和y都能得到z,返回true;

解题新思路:

以Example1为例,发现整个过程中我们向3升水壶倒了3次水,一共倒了9升水,也就是说,外界进入系统(x,y,z)共9升水,系统向外界通过5升水壶倒出5升水,这样9-5=4,

即得到我们想要的4升水。问题转化为判断是否存在整数m和n使得3*m+5*n=4,若存在这样的整数,则说明能得到我们想要的结果,返回true。这是一个纯数学问题,即判断

是否存在整数m和n使得x*m+y*n=z解法是判断z是否为x和y的最大公约数的倍数。问题已经分析完,下面代码求解。


public class WaterAndJugProblem {

public boolean canMeasureWater(int x, int y, int z) {
        if(x+y<z) return false;
        if(z==0) return true;
        return z%gcd(x,y)==0;
        
    }
public int gcd(int x, int y){
if(y==0 ) return x;
if(x==0) return y;
  while(x!=y){
if(x>y) x=x-y;
if(y>x) y=y-x;
}
return y==0?x:y;
}
}

0 0
原创粉丝点击