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
相关推荐
南宫生38 分钟前
贪心算法习题其四【力扣】【算法学习day.21】
学习·算法·leetcode·链表·贪心算法
懒惰才能让科技进步1 小时前
从零学习大模型(十二)-----基于梯度的重要性剪枝(Gradient-based Pruning)
人工智能·深度学习·学习·算法·chatgpt·transformer·剪枝
Ni-Guvara2 小时前
函数对象笔记
c++·算法
测试19982 小时前
2024软件测试面试热点问题
自动化测试·软件测试·python·测试工具·面试·职场和发展·压力测试
泉崎2 小时前
11.7比赛总结
数据结构·算法
你好helloworld2 小时前
滑动窗口最大值
数据结构·算法·leetcode
AI街潜水的八角3 小时前
基于C++的决策树C4.5机器学习算法(不调包)
c++·算法·决策树·机器学习
白榆maple3 小时前
(蓝桥杯C/C++)——基础算法(下)
算法
JSU_曾是此间年少3 小时前
数据结构——线性表与链表
数据结构·c++·算法
sjsjs113 小时前
【数据结构-合法括号字符串】【hard】【拼多多面试题】力扣32. 最长有效括号
数据结构·leetcode