[LeetCode55]Jump Game

来源:互联网 发布:触摸屏查询网站源码 编辑:程序博客网 时间:2024/05/29 19:28

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Analysis:

Note that the A[i] means the maximum jump length. In other words, it is possible that we move j step (<A[i]) when we at A[i], e.g. if A[i]=2, we can move either 1 or 2 steps.
The simple but time-consuming way is O(n^2). Set every future step true according to the A[i]. But this only can pass the small test.
A better idea is use another variable to save the number of steps available. Just a little bit different from the O(n^2) one , see code for more details.

Use one variable to store current maximum jump index

Java

public boolean canJump(int[] A) {        int jmax = 0;        for(int i = 0;i<A.length;i++){        if(i<=jmax){        jmax = Math.max(jmax, A[i]+i);        }else {return false;}        }        return true;     }

c++

bool canJump(int A[], int n) {      int maxCover = 0;    for(int start = 0; start<=maxCover &&start<n;start++){        if(A[start]+start > maxCover)            maxCover = A[start]+start;        if(maxCover >=n-1)            return true;    }    return false;    }



0 0
原创粉丝点击