標籤:style blog http color os io for ar
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.
演算法思路:
維護一個一位元組canAccess,canAccess[i]表示第i點是可達的。初始化canAccess[0] = true;同時,維護一個指標,指向最遠可達距離。以免重複計算;
遍曆數組A,沒遇到一個元素,就更新canAccess數組,當遍曆到某個A中的元素不可達時,跳出迴圈。
代碼如下:
1 public class Solution { 2 public boolean canJump(int[] a) { 3 if (a == null || a.length < 2) 4 return true; 5 boolean[] canAccess = new boolean[a.length]; 6 canAccess[0] = true; 7 int approach = 0; 8 for (int i = 0; i < a.length; i++) { 9 if (!canAccess[i]) break;10 if (i + a[i] <= approach)//該元素無需再處理11 continue;12 for (int j = approach; j <= i + a[i]; j++) {13 if (j == a.length - 1)//若達終點,直接返回14 return true;15 canAccess[j] = true;16 }17 approach = i + a[i] ;//記錄最遠可達點18 }19 return canAccess[a.length - 1];20 }21 }