55. Jump Game
难度:Medium
刷题内容
原题连接
- https://leetcode.com/problems/jump-game/submissions/
内容描述
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.
˼· **- ʱ¼ä¸´ÔÓ¶È: O(N)*- ¿Õ¼ä¸´ÔÓ¶È: O(1)***
¸Õ¿ªÊ¼Ïëµ½µÄ¾ÍÊÇDPµÄ·½·¨£¬µ«ÊÇÓÃDPµÄ»°Ê±¼ä¸´ÔÓ¶ÈΪO(n^2)£¬ºÜÏÔÈ»ÎÒÃÇ¿ÉÒÔ¶ÔËã·¨½øÐÐÓÅ»¯,ÔÚʱ¼ä¸´ÔÓ¶ÈO(n)ÄÚÍê³É¡£ÎÒÃÇÖ»ÐèÒªÅжÏÿһ²½ÄÜ×ßµÄ×îÔ¶µÄ¾àÀë¼´¿É£¬±ÈÈçÊý×é[2,3,1,1,4]£¬µÚÒ»²½Ö»ÄÜ×ßµ½0£¬µÚ¶þ²½ÔÚÇø¼ä[1£¬2]ÖÐÕÒ×îÔ¶µÄ¾àÀëΪ4¡£ÒÀ´ÎÀàÍÆ
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size() <= 1)
return 1;
for(int i = 0,r = 0;i < nums.size() - 1;)
{
int max1 = 0;
while(i <= r)
{
max1 = max(max1,i + nums[i]);
++i;
}
//cout << max1 << endl;
if(max1 >= nums.size() - 1)
return 1;
if(max1 <= r)
return 0;
r = max1;
}
}
};