leetcode - 780. Reaching Points

Description

Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.

The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).

Example 1:

复制代码
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)

Example 2:

复制代码
Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: false

Example 3:

复制代码
Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: true

Constraints:

复制代码
1 <= sx, sy, tx, ty <= 10^9

Solution

Shrink 1by1

The possibilities are like a binary tree, use example 1:

复制代码
			   1,1
			/		\
		1,2			2,1
		/	\		/ \
	1,3		3,2	  2,3 	3,1
	/ \		/ \		/\
  1,4  4,3 3,5 5,2 ...

So instead of searching from the sx, sy, which is the top of the tree, we could start from the leaf, which is the tx, ty

Note that:
t x , t y = { s x , s x + s y s x + s y , s y tx, ty = \begin{cases} sx, sx+sy \\ sx + sy, sy \end{cases} tx,ty={sx,sx+sysx+sy,sy

So every time shrink the smaller one from tx, ty, which means find the parent of the node, until we find the source node.

Time complexity: o ( log ⁡ max ⁡ ( t x , t y ) ) o(\log \max(tx, ty)) o(logmax(tx,ty))

Space complexity: o ( 1 ) o(1) o(1)

Shrink by potential maximum

It's too slow to shrink one node at a time, we could shrink to the number that is larger than sx or sy

Code

Shrink 1by1 (TLE)

python3 复制代码
class Solution:
    def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
        while (tx != sx or ty != sy) and tx >= 1 and ty >= 1:
            if tx > ty:
                tx, ty = tx % ty, ty
            else:
                tx, ty = tx, ty % tx
        return tx == sx and ty == sy

Shrink by potential maximum

python3 复制代码
class Solution:
    def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
        while (tx != sx or ty != sy) and tx >= 1 and ty >= 1:
            if tx > ty:
                multi_factor = max(1, (tx - sx) // ty)
                tx, ty = tx - multi_factor * ty, ty
            else:
                multi_factor = max(1, (ty - sy) // tx)
                tx, ty = tx, ty - tx * multi_factor
        return tx == sx and ty == sy
相关推荐
li星野5 分钟前
FAISS 详解:原理、使用与面试指南——向量检索的基石
面试·职场和发展·faiss
mifengxing5 分钟前
LeetCode热题100——字母异位词分组
java·算法·leetcode·职场和发展·哈希表·hot100
Billlly1 小时前
莫比乌斯反演学习笔记
算法
stolentime2 小时前
CF2066D1 Club of Young Aircraft Builders (easy version)题解
c++·算法·动态规划·组合数学
Dillon Dong2 小时前
【风电控制】高低穿现场失败的原因分析——算法简单但工程复杂
算法·变流器·风电控制·dfig
小欣加油2 小时前
leetcode41 缺失的第一个正数
数据结构·c++·算法·leetcode
I Promise342 小时前
智驾APA_HPA可行驶区域检测算法工程师面试问题整理可参考
算法·面试·职场和发展
智者知已应修善业2 小时前
【51单片机按键控制1分钟正计时倒计时暂停复位】2024-1-2
c++·经验分享·笔记·算法·51单片机
weixin_468466852 小时前
UNet 模型结构从零搭建与实战解析
人工智能·深度学习·算法·机器学习·ai·unet
Useasy_JIJIANYUN3 小时前
合作快讯:极简云呼叫中心(Useasy)正式上架Zoho全球应用市场!
算法