Reaching Points

韶镜
2023-12-01

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)

思路:正着算,TLE,

(x,y)

(x, x+y) (x + y, y)

这个树形结构,永远是个二叉树,那么从终点往起点算,会很快,怎么算?

就是 tx < ty, ty = ty % tx.       tx > ty ,  tx = tx % ty;

这样算到最后一层了,只能有两种情况:

sx == tx && sy <= ty && (ty - sy) % sx == 0; 

sy == ty && sx <= tx && (tx - sx) % sy == 0; 可以找到root,否则就找不到;

class Solution {
    public boolean reachingPoints(int sx, int sy, int tx, int ty) {
        while(sx < tx && sy < ty) {
            if(tx < ty) {
                ty = ty % tx;
            } else {
                // tx > ty;
                tx = tx % ty;
            }
        }
        
        if(sx == tx && sy <= ty  && (ty - sy) % sx == 0) {
            return true;
        } 
        if(sy == ty && sx <= tx && (tx - sx) % sy == 0 ) {
            return true;
        }
        return false;   
    }
}

 

 类似资料:

相关阅读

相关文章

相关问答