题目描述:
从点 (x, y) 可以转换到 (x, x+y) 或者 (x+y, y)。
给定一个起点 (sx, sy) 和一个终点 (tx, ty),如果通过一系列的转换可以从起点到达终点,则返回 True ,否则返回 False。
示例:
输入: sx = 1, sy = 1, tx = 3, ty = 5
输出: True
解释:
可以通过以下一系列转换从起点转换到终点:
(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] 的整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reaching-points
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
搞不懂了,为什么这样子执行的时候不会超时,一提交就超时…
我的思路是:从终点开始递减,每次我们可以发现较大的数字肯定是最后得到的,因此反复递减较大的数字即可,但是会超时????
class Solution {
public boolean reachingPoints(int sx, int sy, int tx, int ty) {
if(sx == tx && sy == ty){
return true;
}
if(tx == ty && tx == 0){
return false;
}
while (tx != 0 && ty != 0 && tx != ty){
if(tx > ty){
tx -= ty;
}else{
ty -= tx;
}
if(tx == sx && ty == sy){
return true;
}
// break;
}
return false;
}
}
其实超时的原因是每次的循环减去的值太小,导致逼近的次数过多,那么我们可以考虑
class Solution {
public boolean reachingPoints(int sx, int sy, int tx, int ty) {
if(sx == tx && sy == ty){
return true;
}
if(tx == ty && tx == 0){
return false;
}
while (tx >= sx && ty >= sy && tx != ty){
if(tx > ty){
tx -= Math.max((tx - sx) / ty, 1) * ty;
}
else{//此时只能有ty减去tx
//ty - sy是目标与起始值在y的差距,我们需要一次减去n * tx达到快速逼近sy的目的
ty -= Math.max((ty - sy) / tx, 1) * tx;
}
if(tx == sx && ty == sy){
return true;
}
}
return false;
}
}