每天三道leetcode——55、

55. 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.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach
the last index.
 
此规则下,能不能到达最后一个位置可转化为求最远能到达的位置问题,可使用贪心算法;
遍历数组中每一个元素,每次得到当前能到达的最远位置reach,reach已经抵达最后一个位置(甚至更远)则跳出循环;
当前位置大于最远位置时,也要跳出循环(考虑数组中某个元素为0的情况)
 
 1 class Solution 
 2 {
 3 public:
 4     bool canJump(vector<int>& nums) 
 5     {
 6         int reach=0;
 7         int n=nums.size();
 8         for(int i=0; i<n; ++i)
 9         {
10             if(i>reach || reach>n-1)
11                 break;
12             reach=max(reach,i+nums[i]);
13         }
14         return reach>=n-1;
15     }
16 };
 

猜你喜欢

转载自www.cnblogs.com/Joezzz/p/9579151.html
今日推荐