Weekly Contest 71 leetcode 780. Reaching Points

來源:互聯網
上載者:User

A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).

Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False.

Examples:Input: sx = 1, sy = 1, tx = 3, ty = 5Output: TrueExplanation: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)Input: sx = 1, sy = 1, tx = 2, ty = 2Output: FalseInput: sx = 1, sy = 1, tx = 1, ty = 1Output: True

Note: sx, sy, tx, ty will all be integers in the range [1, 10^9]. 這道題主要是要找到時間複雜度較小的思路。我無論怎麼做,要麼TLE,要麼StackOverFlow,無奈,只能看看solutions,看看大神的解法。

solutions:https://leetcode.com/problems/reaching-points/solution/,solutions 前幾個給的都是TLE的解法,即不能通過測試案例。主要是看最後一個AC的解法。

Approach #1: Exhaustive Search [Time Limit Exceeded]

class Solution {    public boolean reachingPoints(int sx, int sy, int tx, int ty) {        if (sx > tx || sy > ty) return false;        if (sx == tx && sy == ty) return true;        return reachingPoints(sx+sy, sy, tx, ty) || reachingPoints(sx, sx+sy, tx, ty);    }}
Complexity Analysis

Time Complexity: O(2^{tx + ty})O(2tx+ty), a loose bound found by considering every move as (x, y) -> (x+1, y)or (x, y) -> (x, y+1) instead.

Space Complexity: O(tx * ty)O(tx∗ty), the size of the implicit call stack. Approach #2: Dynamic Programming [Time Limit Exceeded]

Intuition and Algorithm

As in Approach #1, we search the children of every point recursively, except we use a set seen so that we don't repeat work.

import java.awt.Point;class Solution {    Set<Point> seen;    int tx, ty;    public boolean reachingPoints(int sx, int sy, int tx, int ty) {        seen = new HashSet();        this.tx = tx;        this.ty = ty;        search(new Point(sx, sy));        return seen.contains(new Point(tx, ty));    }    public void search(Point P) {        if (seen.contains(P)) return;        if (P.x > tx || P.y > ty) return;        seen.add(P);        search(new Point(P.x + P.y, P.y));        search(new Point(P.x, P.x + P.y));    }}

Complexity Analysis

Time Complexity: O(tx * ty)O(tx∗ty), as at most tx * ty points are searched once per point.

Space Complexity: O(tx * ty)O(tx∗ty), the size of the implicit call stack. Approach #3: Work Backwards (Naive Variant) [Time Limit Exceeded]

Intuition

Every parent point (x, y) has two children, (x, x+y) and (x+y, y). However, every point (x, y) only has one parent candidate (x-y, y) if x >= y, else (x, y-x). This is because we never have points with negative coordinates.

Looking at previous successive parents of the target point, we can find whether the starting point was an ancestor. For example, if the target point is (19, 12), the successive parents must have been (7, 12), (7, 5), and (2, 5); so (2, 5) is a starting point of (19, 12).

Algorithm

Repeatedly subtract the smaller of {tx, ty} from the larger of {tx, ty}. The answer is true if and only if we eventually reach sx, sy.

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

Complexity Analysis

Time Complexity: O(\max(tx, ty))O(max(tx,ty)). If say ty = 1, we could be subtracting tx times.

Space Complexity: O(1)O(1). Approach #4: Work Backwards (Modulo Variant) [Accepted]

Intuition

As in Approach #3, we work backwards to find the answer, trying to transform the target point to the starting point via applying the parent operation (x, y) -> (x-y, y) or (x, y-x) [depending on which one doesn't have negative coordinates.]

We can speed up this transformation.

Algorithm

當 tx > ty  時,找父母的操作就是 tx - ty, 直到 tx = tx % ty 為止。當 tx > ty 和 ty > sy 都滿足時,我們可以使用 tx %= ty 來代替 while tx > ty: tx -= ty ,會更快。

當 tx > ty 且 ty = sy  時,我們知道 ty 不能再減了,所以只有 tx 會改變,並且只會通過 一步步地減去ty  來改變。所以,使用 (tx - sx) % ty == 0 會更高效。

ty > tx  的情形同理。可以一直這樣做,直到 tx == ty, 此時不需要再做 move 了。

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

Complexity Analysis

Time Complexity: O(\log(\max{(tx, ty)}))O(log(max(tx,ty))). The analysis is similar to the analysis of the Euclidean algorithm, and we assume that the modulo operation can be done in O(1)O(1) time.

Space Complexity: O(1)O(1).


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.