★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝()➤GitHub地址:➤原文地址: ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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 = 5Output: TrueExplanation: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 = 2Output: FalseInput: sx = 1, sy = 1, tx = 1, ty = 1Output: 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 == 011 }12 } else {13 if (tx > sx) {14 ty %= tx15 } else {16 return (ty - sy) % tx == 017 } 18 }19 }20 return false21 }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 = tx15 var ty = ty16 while tx >= sx && ty >= sy {17 if tx == sx && ty == sy {18 return true19 }20 if tx > ty {21 var r = tx%ty22 if sx > r {23 return ty == sy && (sx-r)%ty == 024 }25 tx = r26 } else {27 var r = ty%tx28 if sy > r {29 return tx == sx && (sy-r)%tx == 030 }31 ty = r32 }33 }34 return false35 }36 }