您当前的位置: 首页 >  leetcode

孑渡

暂无认证

  • 2浏览

    0关注

    178博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Leetcode】每日一题:到达终点

孑渡 发布时间:2022-04-09 12:31:29 ,浏览量:2

到达终点

给定四个整数 sx , sy ,tx 和 ty,如果通过一系列的转换可以从起点 (sx, sy) 到达终点 (tx, ty),则返回 true,否则返回 false。 从点 (x, y) 可以转换到 (x, x+y) 或者 (x+y, y)。 来源:力扣(LeetCode)

AC代码
class Solution:
    def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
        dx, dy = tx, ty
        if dx == sx and dy == sy:
            return True
        while dx > 0 and dy > 0:
            if dx > dy:
                dx = dx - max((dx - sx) // dy, 1) * dy
            else:
                dy = dy - max((dy - sy) // dx, 1) * dx
            if dx == sx and dy == sy:
                return True
        else:
            return False

官方代码
class Solution:
    def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
        while sx  sy:
            if tx > ty:
                tx %= ty
            else:
                ty %= tx
        if tx == sx and ty == sy:
            return True
        elif tx == sx:
            return ty > sy and (ty - sy) % tx == 0
        elif ty == sy:
            return tx > sx and (tx - sx) % ty == 0
        else:
            return False


# 作者:LeetCode-Solution

1、直接取模也是个不错的选择,但是这样的话需要考虑当tx不能再减小或者其他的情况,感觉不如直接tx < 0来的方便

关注
打赏
1663211900
查看更多评论
立即登录/注册

微信扫码登录

0.1865s