★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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 }