365. 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.

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.

Example 1: (From the famous "Die Hard" example)

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

Example 2:

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

Credits:

Special thanks to @vinod23 for adding this problem and creating all test cases.


数学方法不会。。。直接朴素生成+hash也过了。。虽然很慢很慢。。可是实用好想啊~

首先可以根据两个罐子的和以及差,生成新的度量值。

每次新生成的度量值,例如第一次生成的2、8,那么看这新的度量值是不是比其中一个罐子的容量小,例如2比3和5都小,

那么2就可以放在第一个罐子中,和第二个罐子作差作和生成3、7,也可以放在第二个罐子中,和第一个罐子作差作和得到1、5

然后新生成的度量值又可以做类似的操作。。。

度量值是不断增加的,如果某一轮出现了需要的度量值,直接返回找到了。如果一轮中没有新的度量值产生了,再搜下去也不会有新的度量值了,直接结束就可以。

 public static boolean canMeasureWater(int x, int y, int z)
	{
	    
	    if(z==0)
	        return true;
		HashSet<Integer> hashset=new HashSet<>();
		HashSet<Integer> checkhashset=new HashSet<>();
		if(z>x+y)
			return false;
		
		int a=Math.min(x, y);
		int b=Math.max(x, y);
		
		hashset.add(a);
		hashset.add(b);
		checkhashset.add(a+b);
		checkhashset.add(b-a);
		int presize=0;
		
		
		while(true)
		{
			Iterator<Integer> it=checkhashset.iterator();
			ArrayList<Integer> arraylist=new ArrayList<>();
			while(it.hasNext())
			{
				int num=it.next();
				it.remove();
				if(num<=a+b)
				{
					hashset.add(num);
					arraylist.add(num);
				}
				
			}
			
			if(hashset.contains(z))
				return true;
			
			
			for(int num  :arraylist)
			{
				if(num<=a)
				{
					if(!hashset.contains(b+num))
						checkhashset.add(b+num);
					if(!hashset.contains(b-num))
						checkhashset.add(b-num);
				}
				if(num<=b)
				{
					if(!hashset.contains(a+num))
						checkhashset.add(a+num);
					
					int temp=a-num>0?a-num:num-a;
					if(!hashset.contains(temp))
					checkhashset.add(temp);
				}
			}
			
			if(hashset.size()==presize)
				break;
			
			presize=hashset.size();
			
		}
		
		return false;
	}


-------------------------------------------------------------------------------------------

还是贴一下高级点的数学方法,摘自

https://discuss.leetcode.com/topic/49238/math-solution-java-solution


This is a pure Math problem. We need the knowledge of number theory to cover the proof and solution. No idea why microsoft uses this problem in real interview.

The basic idea is to use the property of Bézout's identity and check if z is a multiple of GCD(x, y)

Quote from wiki:

Bézout's identity (also called Bézout's lemma) is a theorem in the elementary theory of numbers:

let a and b be nonzero integers and let d be their greatest common divisor. Then there exist integers x
and y such that ax+by=d

In addition, the greatest common divisor d is the smallest positive integer that can be written as ax + by

every integer of the form ax + by is a multiple of the greatest common divisor d.

If a or b is negative this means we are emptying a jug of x or y gallons respectively.

Similarly if a or b is positive this means we are filling a jug of x or y gallons respectively.

x = 4, y = 6, z = 8.

GCD(4, 6) = 2

8 is multiple of 2

so this input is valid and we have:

-1 * 4 + 6 * 2 = 8

In this case, there is a solution obtained by filling the 6 gallon jug twice and emptying the 4 gallon jug once. (Solution. Fill the 6 gallon jug and empty 4 gallons to the 4 gallon jug. Empty the 4 gallon jug. Now empty the remaining two gallons from the 6 gallon jug to the 4 gallon jug. Next refill the 6 gallon jug. This gives 8 gallons in the end)

See wiki:

Bézout's identity

and comments in the code

public boolean canMeasureWater(int x, int y, int z) {
    //limit brought by the statement that water is finallly in one or both buckets
    if(x + y < z) return false;
    //case x or y is zero
    if( x == z || y == z || x + y == z ) return true;
    
    //get GCD, then we can use the property of Bézout's identity
    return z%GCD(x, y) == 0;
}

public int GCD(int a, int b){
    while(b != 0 ){
        int temp = b;
        b = a%b;
        a = temp;
    }
    return a;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值