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]
, returntrue
.A =
[3,2,1,0,4]
, returnfalse
.
贪心算法。
在Leetcode上的第100题,mark下。
一开始我用了动态规划,维护了一个访问过的数组isVisited[n]时间复杂度o(n^2)。其实完全没必要,只要维护一个标记当前可以跳转到的地址的变量right即可。如果right>=n-1,则成功,否则失败。
class Solution { public: bool canJump(int A[], int n) { int right = 0; for(int i = 0; i <= right; i++){ right = right > i + A[i]? right: i + A[i]; if(right >= n - 1) return true; } return false; } };
Pingback: 刷题总结 - Bo Song's Personal Website