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
相关推荐
qq_429879671 小时前
省略号和可变参数模板
开发语言·c++·算法
飞川撸码2 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
Neil今天也要学习2 小时前
永磁同步电机参数辨识算法--IPMSM拓展卡尔曼滤波全参数辨识
单片机·嵌入式硬件·算法
yzx9910133 小时前
基于 Q-Learning 算法和 CNN 的强化学习实现方案
人工智能·算法·cnn
亮亮爱刷题3 小时前
算法练习-回溯
算法
眼镜哥(with glasses)4 小时前
蓝桥杯 国赛2024python(b组)题目(1-3)
数据结构·算法·蓝桥杯
int型码农8 小时前
数据结构第八章(一) 插入排序
c语言·数据结构·算法·排序算法·希尔排序
UFIT9 小时前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面9 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked939 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise