LeetCode 365 Water and Jug Problem
来源:互联网 发布:乌克兰 知乎 编辑:程序博客网 时间:2024/05/21 05:55
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 zlitres 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 = 4Output: True
Example 2:
Input: x = 2, y = 6, z = 5Output: False
题意:
给定两个容量分别为x和y升的罐子。提供无限容量的水。你需要判断用这两个罐子是否可以恰好量出z升的体积。到最后量出的z升体积可以由一到两个罐子装着。
允许的操作包括:
1、将任意罐子灌满。
2、将任意罐子清空。
3、将任意罐子的水倒入另一个罐子,直到另一个罐子倒满或者自己为空为止。
设c为x、y的最大公约数,则x/c、y/c都为整数,分别设m=x/c,n=y/c,请看以下证明过程:
ax+by
=a*c*x/c+b*c*y/c
=a*c*m+b*c*n
= a'*c+b'*c (设a'=a*m,b'=b*n)
= (a'+b')*c。
ax+by== (a'+b')*c,其中c为x,y的最大公约数,a',b'为整数,若z = ax+by=(a'+b')*c,则z必须可以整除c,因此题意又等价于,判断z是否可以整除x,y的最大公约数。
public boolean canMeasureWater(int x, int y, int z) {return z == 0 || (z <= x + y && z % getGcd(x, y) == 0);}/** * 最大公约数 */private int getGcd(int a, int b) {return b == 0 ? a : getGcd(b, a % b);}
- LeetCode 365 Water and Jug Problem
- [leetcode-365]Water and Jug Problem(java)
- leetcode:数学:Water and Jug Problem(365)
- 【Leetcode】Water and Jug Problem
- leetcode:Water and Jug Problem
- leetcode---Water and Jug Problem
- [LeetCode] Water and Jug Problem
- [LeetCode]problem 365. Water and Jug Problem
- leetcode.365. Water and Jug Problem
- LeetCode 365. Water and Jug Problem
- LeetCode—365. Water and Jug Problem
- Leetcode 365. Water and Jug Problem
- Leetcode 365. Water and Jug Problem[medium]
- LeetCode 365. Water and Jug Problem
- Leetcode 365. Water and Jug Problem
- [LeetCode]365. Water and Jug Problem
- [leetcode]365. Water and Jug Problem
- leetcode 365. Water and Jug Problem
- Codeforces Round #360 (Div. 2) B. Lovely Palindromes
- linux服务器使用SSH Secure Shell Client部署tomcat
- 输入adb shell 时 提示error: more than one device and emulator
- redis 配置文件详解
- Linux内核---7.Makefile学习笔记
- LeetCode 365 Water and Jug Problem
- netstat已经out,取代他的是ss
- Tomcat
- shell 脚本的基础
- 1016 ProblemP
- 使用DOM4J解析xml
- (1)MySQL语句规范
- 探索linux管道的容量
- Linux内核---8.filechk函数分析