Sunday, May 17, 2015

Jump Game I

来源:Leetcode

原帖:http://oj.leetcode.com/problems/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.
Solution: Updated solution: try every reachable index.

代码:
 class Solution {  
 public:  
   bool canJump(int A[], int n) {  
     int start = 0, farthest = 0; // farthest: 最多可以到达的状态  
     while (start <= farthest && farthest < n - 1) {  
       farthest = max(farthest, start + A[start]);  
       start++;  
     }  
     return farthest >= (n-1);  
   }  
 };  

No comments:

Post a Comment