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
相关推荐
student.J19 分钟前
傅里叶变换
python·算法·傅里叶
五味香25 分钟前
C++学习,动态内存
java·c语言·开发语言·jvm·c++·学习·算法
Beauty.56831 分钟前
P1328 [NOIP2014 提高组] 生活大爆炸版石头剪刀布
数据结构·c++·算法
Aurora200532 分钟前
蓝桥杯2024省C
c语言·算法·蓝桥杯
爱棋笑谦33 分钟前
二叉树计算
java·开发语言·数据结构·算法·华为od·面试
小鱼在乎1 小时前
动态规划---最长回文子序列
算法·动态规划
xiaobai12 31 小时前
二叉树的遍历【C++】
开发语言·c++·算法
吱吱鼠叔1 小时前
MATLAB数学规划:2.线性规划
算法·机器学习·matlab
声学黑洞仿真工作室2 小时前
Matlab Delany-Bazley和Miki模型预测多孔材料吸声性能
开发语言·人工智能·算法·matlab·微信公众平台
机器学习之心2 小时前
选址模型 | 基于混沌模拟退火粒子群优化算法的电动汽车充电站选址与定容(Matlab)
算法·选址模型