Leetcode #780. Reaching Points
题目
https://leetcode.com/problems/reaching-points/description/
代码
一开始的思路是逆向推,目的坐标(tx, ty)肯定是由(tx-ty, ty)或(tx, ty-tx),但是坐标限定不为负数,因此比较tx、ty的大小可以唯一确定上一步的步骤
于是有:
class Solution {
public:
bool reachingPoints(int sx, int sy, int tx, int ty) {
while (tx >= sx && ty >= sy) {
if (sx == tx && ty == sy) return true;
else {
if (tx == sx) return (ty - sy) % sx == 0;
if (ty == sy) return (tx - sx) % ty == 0;
if (tx > ty) tx-=ty;
else ty-=tx;
}
}
return false;
}
};
不加if (tx == sx) return (ty - sy) % sx == 0; if (ty == sy) return (tx - sx) % ty == 0;
会TLE。~~
后来看了其他人的代码,才想起来可以这样做:
class Solution {
public:
bool reachingPoints(int sx, int sy, int tx, int ty) {
while(sx < tx && sy < ty) {
if(tx < ty) ty %= tx;
else tx %= ty;
}
return (sx == tx && (ty-sy) % sx == 0) ||
(sy == ty && (tx-sx) % sy == 0);
}
};