Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 1871. Jump Game VII #218

Open
Woodyiiiiiii opened this issue Mar 5, 2023 · 0 comments
Open

Leetcode 1871. Jump Game VII #218

Woodyiiiiiii opened this issue Mar 5, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题我还想着用BFS来做,但发现在最坏情况下(minJump=1, maxJump=99999)会达到O(n^2)的复杂度,那么BFS就不能做了。

再看下题目,把重点放在minJump和maxJump这两个变量上,有点类似sliding window / two pointers。遍历数组,到某个点i,如何判断这个点i是否在之前的某个有效j的辐射范围[j+minJump, j+maxJump]里呢?直接判断i-minJump/i-maxJump就行了。如果在多个范围内,就用一个变量叠加表示。

class Solution {
    public boolean canReach(String s, int minJump, int maxJump) {
        int n = s.length();
        if (s.charAt(n - 1) == '1') {
            return false;
        }
        boolean[] dp = new boolean[n];
        dp[0] = true;
        int prev = 0;
        for (int i = 1; i < n; ++i) {
            if (i >= minJump) {
                prev += dp[i - minJump] ? 1 : 0;
            }
            if (i > maxJump) {
                prev -= dp[i - maxJump - 1] ? 1 : 0;
            }
            dp[i] = prev > 0 && s.charAt(i) == '0';
        }
        return dp[n - 1];
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant