Jump Game


題目:

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

 

解決:

  難點是跳到值爲0的位置,是不是最後一個位置。

 

public class Solution {
    public boolean canJump(int[] A) {
        int idx = 0;
        while(true){
            if (A[idx]+idx >= A.length || A[idx]==0 && idx==A.length-1)//跳過了,或最後一個是0
                return true;
            else if (A[idx]==0 && idx!=A.length-1)//跳到值爲0的,但不是最後一個位置
                return false;
            else
                idx +=A[idx];
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章