在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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:
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 有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水? 如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。 你允许:
示例 1: (From the famous "Die Hard" example) 输入: x = 3, y = 5, z = 4 输出: True 示例 2: 输入: 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 }
|
请发表评论