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.spa
For example:
A = [2,3,1,1,4]
, return true
.code
A = [3,2,1,0,4]
, return false
.blog
開始的想法比較複雜,O(N^2)的複雜度,大數據測試超時了,而後改進了一下,設一個標誌位表示第一個不可達的下標,最後判斷最後一個元素是否可達,複雜度爲O(N),代碼以下element
1 public boolean canJump(int[] A) { 2 if (A.length <= 1) { 3 return true; 4 } 5 boolean p[] = new boolean[A.length]; 6 p[0] = true; 7 int pos = 1; 8 for (int i = 0; i < A.length; i++) { 9 if (p[i]) { 10 for (int j = pos - i; j <= A[i] && i + j < A.length; j++) { 11 p[i + j] = true; 12 } 13 } 14 if (p[p.length - 1]) { 15 return true; 16 } 17 } 18 return false; 19 }
看了下網上的,這個寫的比較簡單,複雜度也是O(N),思路就是找到第一個不可達的下標,判斷是否是大於最後一個元素的下標,代碼以下it
1 public boolean canJump(int[] A) { 2 int max = 0; 3 for (int i = 0; i < A.length && i <= max; i++) { 4 max = A[i] + i > max ? A[i] + i : max; 5 } 6 return max >= A.length - 1; 7 }
貪心策略,局部最優等於全局最優?io
差距就是原本5行代碼能搞定的我卻要寫15行。。。0.0ast