zoukankan      html  css  js  c++  java
  • [leetcode]Jump Game

    一开始用了DP,大数据超时了。

    超时的版本:

    public class Solution {
        public boolean canJump(int[] A) {
            // Start typing your Java solution below
            // DO NOT write main() function
            int len = A.length;
            if (len == 0 || len == 1) return true;
            boolean m[] = new boolean[len];
            m[0] = true;
            for (int i = 0; i < len; i++) {
                for (int j = 0; j < i; j++) {
                    if (i - j <= A[j] && m[j]) {
                        m[i] = true;
                        continue;
                    }
                }
            }
            
            return m[len-1];
        }
    }
    

    后来也思维一转,直接从前往后扫就是了,,但感觉复杂度没有本质区别,果然还是超时。

    后来再看了网上的参考,理解到本质上,只有A[i]为0(或负数)的情况下,才会不能继续往前跳,那么从左向右扫,并维持一个当前能跳到的最远的距离就行了。

    public class Solution {
        public boolean canJump(int[] A) {
            // Start typing your Java solution below
            // DO NOT write main() function
            int len = A.length;
            if (len == 0 || len == 1) return true;
            int max = 0;
            for (int i = 0; i < len; i++) {
                if (A[i] <= 0 && i == max) {
                    return false;
                }
                else {
                    if (A[i] > 0 && A[i] + i > max) {
                        max = A[i] + i;
                    }
                }
                if (max >= len - 1) return true;
            }
            return false;
        }
    }
    

    第二刷:Annie的版本更漂亮 https://github.com/AnnieKim/LeetCode/blob/master/JumpGame.h

    class Solution {
    public:
        bool canJump(int A[], int n) {
            int maxLen = 0;
            for (int i = 0; i < n; i++)
            {
                if (maxLen >= n - 1)
                    return true;
                if (i > maxLen)
                    return false;
                int curMax = i + A[i];
                maxLen = max(maxLen, curMax);
            }
        }
    };
    

      

  • 相关阅读:
    51 Nod 1068 Bash游戏v3
    51 Nod Bash 游戏v2
    51 Nod 1073 约瑟夫环
    UVA 12063 Zeros and ones 一道需要好好体会的好题
    51 Nod 1161 Partial sums
    2018中国大学生程序设计竞赛
    UVA 11971 Polygon
    UVA 10900 So do you want to be a 2^n-aire?
    UVA 11346 Possibility
    python with as 的用法
  • 原文地址:https://www.cnblogs.com/lautsie/p/3251680.html
Copyright © 2011-2022 走看看