[LeetCode] 55. Jump Game Java


題目:

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.

題意及分析:根據題目要求,數組里的每個元素表示從該位置可以跳出的最遠距離,要求問從第一個元素(index=0)開始,能否達到數組的最后一個元素,這里認為最后一個元素為終點。這里是到達,說明超過也行,看下圖能更好的理解題意。

 

所以這里可以使用貪心算法,計算出某個點時 能夠跳出的最大距離(當前的最大值和(當前點+能跳出的最大距離)的較大的值),如果能跳出的最大距離大於最后一個點的位置,那么返回true,能到達;如果到達當前點后,不能在往后跳,那么不能達到最后點,返回false。

代碼:

public class Solution {
    public boolean canJump(int[] nums) {
         if(nums.length<1)
        	return false;
        if(nums.length==1)
        	return true;
        
        int max=0;		//記錄到當前點時能到達的最大位置
        for(int i=0;i<nums.length-1;i++){
        	max=Math.max(max, i+nums[i]);
        	if(max<i+1){		//如果到達不了后續點(這里通常情況為 當前點為0,前面的能達到的最大點 為當前點或者當前點前面的點),返回false
        // 		System.out.println(false);
        		return false;
        	}
        	if(max>=(nums.length-1)){
        // 		System.out.println(true);
        		return true;
        	}
        }
        return false;
    }
}

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM