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

到达终点

给定四个整数 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 < tx != ty > 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来的方便

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值