[Leetcode] 365. Water and Jug Problem 解题报告
来源:互联网 发布:李刚疯狂java讲义 编辑:程序博客网 时间:2024/06/04 17:46
题目:
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 = 4Output: True
Example 2:
Input: x = 2, y = 6, z = 5Output: False
思路:
这是一道数学题目(不过顺便也考查了一下求最大公约数的辗转相除法^_^),具体解释在youtube上面可以看到: "Die Hard" example,我自己也没明白具体原理。不过总体来讲要用x升和y升大小的两个桶精确量出z升水,其充要条件是:1)z必须小于等于(x + y)(否则装不下);2)z必须可以除尽x和y的最大公约数。其中条件1)显而易见;但是条件2)是为什么呢?求解释。
代码:
class Solution {public: bool canMeasureWater(int x, int y, int z) { if(z > x + y) { return false; } return z == 0 ? true : z % gcd(x, y) == 0; }private: int gcd(int x, int y) { return y == 0 ? x : gcd(y, x % y); }};
阅读全文
0 0
- [leetcode] 365. Water and Jug Problem 解题报告
- leetcode 365. Water and Jug Problem 解题报告
- [Leetcode] 365. 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
- leetcode 365. Water and Jug Problem
- 【Leetcode】Water and Jug Problem
- leetcode:Water and Jug Problem
- leetcode---Water and Jug Problem
- 为什么不能通过返回值类型区分重载?
- 模板
- USACO最长前缀(trie练习题)
- 【Zookeeper】概述
- linux总结笔记(一)linux/ubuntu下ping www.baidu.com失败总结(校园网)
- [Leetcode] 365. Water and Jug Problem 解题报告
- 设计模式——单例模式(php)
- Flask实战2问答平台-父模板抽离(登录注册界面)
- 文本编辑部署servlet
- POJ2441-Arrange the Bulls
- Parcel_进程间数据传递
- CodeForces
- (LeetCode)Search Insert Position --- 二分搜索
- hdu6165 (缩点+拓扑排序)