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
相关推荐
莫叫石榴姐28 分钟前
SQL百题斩:从入门到精通,一站式解锁数据世界
大数据·数据仓库·sql·面试·职场和发展
学Linux的语莫30 分钟前
机器学习数据处理
java·算法·机器学习
earthzhang20211 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
你总是一副不开心的样子(´ . .̫ .1 小时前
一、十天速通Java面试(第三天)
java·面试·职场和发展·java面试
2301_803554523 小时前
C++联合体(Union)详解:与结构体的区别、联系与深度解析
java·c++·算法
sali-tec3 小时前
C# 基于halcon的视觉工作流-章42-手动识别文本
开发语言·人工智能·算法·计算机视觉·c#·ocr
SandySY4 小时前
品三国谈人性
算法·架构
小欣加油4 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗4 小时前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗4 小时前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展