[Swift]LeetCode780. 到达终点 | Reaching Points
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10542023.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
A move consists of taking a point (x, y)
and transforming it to either (x, x+y)
or (x+y, y)
.
Given a starting point (sx, sy)
and a target point (tx, ty)
, return True
if and only if a sequence of moves exists to transform the point (sx, sy)
to (tx, ty)
. Otherwise, return False
.
Examples: Input: sx = 1, sy = 1, tx = 3, ty = 5 Output: True Explanation: One series of moves that transforms the starting point to the target is: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5) Input: sx = 1, sy = 1, tx = 2, ty = 2 Output: False Input: sx = 1, sy = 1, tx = 1, ty = 1 Output: True
Note:
sx, sy, tx, ty
will all be integers in the range[1, 10^9]
.
从点 (x, y)
可以转换到 (x, x+y)
或者 (x+y, y)
。
给定一个起点 (sx, sy)
和一个终点 (tx, ty)
,如果通过一系列的转换可以从起点到达终点,则返回 True
,否则返回 False
。
示例: 输入: sx = 1, sy = 1, tx = 3, ty = 5 输出: True 解释: 可以通过以下一系列转换从起点转换到终点: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5) 输入: sx = 1, sy = 1, tx = 2, ty = 2 输出: False 输入: sx = 1, sy = 1, tx = 1, ty = 1 输出: True
注意:
sx, sy, tx, ty
是范围在[1, 10^9]
的整数。
Runtime: 4 ms
Memory Usage: 18.4 MB
1 class Solution { 2 func reachingPoints(_ sx: Int, _ sy: Int, _ tx: Int, _ ty: Int) -> Bool { 3 if tx < sx || ty < sy {return false} 4 if tx == sx && (ty - sy) % sx == 0 {return true} 5 if ty == sy && (tx - sx) % sy == 0 {return true} 6 return reachingPoints(sx, sy, tx % ty, ty % tx) 7 } 8 }
4ms
1 class Solution { 2 func reachingPoints(_ sx: Int, _ sy: Int, _ tx: Int, _ ty: Int) -> Bool { 3 var tx = tx, ty = ty 4 while tx >= sx && ty >= sy { 5 if tx == ty {break} 6 if tx > ty { 7 if ty > sy { 8 tx %= ty 9 } else { 10 return (tx - sx) % ty == 0 11 } 12 } else { 13 if (tx > sx) { 14 ty %= tx 15 } else { 16 return (ty - sy) % tx == 0 17 } 18 } 19 } 20 return false 21 } 22 }
8ms
1 class Solution { 2 func gcd(_ a: Int, _ b: Int) -> Int { 3 if a < b { 4 return gcd(b, a) 5 } 6 if b == 0 { 7 return a 8 } 9 return gcd(b, a%b) 10 } 11 12 func reachingPoints(_ sx: Int, _ sy: Int, _ tx: Int, _ ty: Int) -> Bool { 13 14 var tx = tx 15 var ty = ty 16 while tx >= sx && ty >= sy { 17 if tx == sx && ty == sy { 18 return true 19 } 20 if tx > ty { 21 var r = tx%ty 22 if sx > r { 23 return ty == sy && (sx-r)%ty == 0 24 } 25 tx = r 26 } else { 27 var r = ty%tx 28 if sy > r { 29 return tx == sx && (sy-r)%tx == 0 30 } 31 ty = r 32 } 33 } 34 return false 35 } 36 }