title: ' 780. 到達(dá)終點(diǎn) (Reaching Points)'
date: 2019-01-17 17:10:17
categories: leetcode
tags: [leetcode,算法, java]
從點(diǎn) (x, y)
可以轉(zhuǎn)換到 (x, x+y)
或者 (x+y, y)
。
給定一個(gè)起點(diǎn) (sx, sy)
和一個(gè)終點(diǎn) (tx, ty)
,如果通過一系列的轉(zhuǎn)換可以從起點(diǎn)到達(dá)終點(diǎn)乡括,則返回 True
频蛔,否則返回 False
。
示例:
輸入: sx = 1, sy = 1, tx = 3, ty = 5
輸出: True
解釋:
可以通過以下一系列轉(zhuǎn)換從起點(diǎn)轉(zhuǎn)換到終點(diǎn):
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
輸入: sx = 1, sy = 1, tx = 2, ty = 2
輸出: False
輸入: sx = 1, sy = 1, tx = 1, ty = 1
輸出: True
注意:
-
sx, sy, tx, ty
是范圍在[1, 10^9]
的整數(shù)眠饮。
由于本題按照題目給的思路正向一步一步走下去會(huì)存在多種情況,我們可以逆向推導(dǎo)。反推起點(diǎn)侣肄,因?yàn)檫@樣只存在兩種種情況。
if : tx > ty then : tx = tx % ty
if : ty > tx then : ty = ty % tx
java代碼
class Solution {
public boolean reachingPoints(int sx, int sy, int tx, int ty) {
while(tx > sx && ty > sy) {
if (tx > ty) {
tx = tx % ty;
} else {
ty = ty % tx;
}
}
if (tx == sx) {
return (ty - sy) % tx == 0;
} else if(ty == sy) {
return (tx - sx) % ty == 0;
} else {
return false;
}
}
}
python代碼
class Solution:
def reachingPoints(self, sx, sy, tx, ty):
"""
:type sx: int
:type sy: int
:type tx: int
:type ty: int
:rtype: bool
"""
while tx > sx and ty > sy:
if tx > ty:
tx = tx % ty
else:
ty = ty % tx
if tx == sx:
return (ty - sy) % sx == 0
if ty == sy:
return (tx - sx) % sy == 0
return False