★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-funhuliu-ex.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.html
If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.git
Operations allowed:github
Example 1: (From the famous "Die Hard" example)微信
Input: x = 3, y = 5, z = 4 Output: True
Example 2:spa
Input: x = 2, y = 6, z = 5 Output: False
有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断可否经过使用这两个水壶,从而能够获得刚好 z升 的水?code
若是能够,最后请用以上水壶中的一或两个来盛放取得的 z升 水。htm
你容许:blog
示例 1: (From the famous "Die Hard" example)ci
输入: x = 3, y = 5, z = 4 输出: True
示例 2:get
输入: x = 2, y = 6, z = 5 输出: False
8ms
1 class Solution { 2 func canMeasureWater(_ x: Int, _ y: Int, _ z: Int) -> Bool { 3 return z == 0 || (x + y >= z && z % gcd(x, y) == 0) 4 } 5 6 func gcd(_ x:Int,_ y:Int) -> Int 7 { 8 return y == 0 ? x : gcd(y, x % y) 9 } 10 }
8ms
1 class Solution { 2 func canMeasureWater(_ x: Int, _ y: Int, _ z: Int) -> Bool { 3 guard z <= x + y else { 4 return false 5 } 6 7 let divisor = greatestCommonDivisor(x, y) 8 9 return z == 0 ? true : z % divisor == 0 10 } 11 12 func greatestCommonDivisor(_ x: Int, _ y: Int) -> Int { 13 14 if y == 0 { 15 return x 16 } 17 18 return greatestCommonDivisor(y, x % y) 19 } 20 }
12ms
1 class Solution { 2 func canMeasureWater(_ x: Int, _ y: Int, _ z: Int) -> Bool { 3 func gcd(x: Int, y: Int) -> Int { 4 if y == 0 { 5 return x 6 } else { 7 return gcd(x: y, y: x%y) 8 } 9 } 10 11 if z == 0 { 12 return true 13 } 14 if x + y < z { 15 return false 16 } else { 17 return z % gcd(x: x, y: y) == 0 18 } 19 } 20 }