[leetcode 55. Jump Game]week 7
2017-07-07 01:58
453 查看
一、题目
Given anarray of non-negative integers, you are initially positioned at the first indexof the array.
Each element in the array represents your maximum jumplength 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.
二、代码
class Solution {
public:
bool canJump(vector<int>& nums) {
int maxjump=1;
for (int i=0;i<maxjump;i++)
{
if (maxjump>nums.size())
break;
if (i+nums[i]+1 > maxjump)
maxjump=i+nums[i]+1;
}
if (maxjump>=nums.size())
return true;
else
return false;
}
};
三、思路
要到达最后一步则判断每一步后更新的可到达最大步数即可,所以用贪婪算法从第一步起每走一步比较原最大值与i+A[i]+1并更新,到最后若最大值大于容器大小(即最后一步)即可。此种解题方法时间复杂度为O(n)
Given anarray of non-negative integers, you are initially positioned at the first indexof the array.
Each element in the array represents your maximum jumplength 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.
二、代码
class Solution {
public:
bool canJump(vector<int>& nums) {
int maxjump=1;
for (int i=0;i<maxjump;i++)
{
if (maxjump>nums.size())
break;
if (i+nums[i]+1 > maxjump)
maxjump=i+nums[i]+1;
}
if (maxjump>=nums.size())
return true;
else
return false;
}
};
三、思路
要到达最后一步则判断每一步后更新的可到达最大步数即可,所以用贪婪算法从第一步起每走一步比较原最大值与i+A[i]+1并更新,到最后若最大值大于容器大小(即最后一步)即可。此种解题方法时间复杂度为O(n)
相关文章推荐
- leetcode解题之45. Jump Game II&55. Jump Game java (跳跃游戏)
- [LeetCode] 55. Jump Game
- [LeetCode] 55. Jump Game 跳跃游戏
- LeetCode week 6 : Jump Game
- Leetcode 55. Jump Game (Medium) (cpp)
- LeetCode--55. Jump Game
- LeetCode 55. Jump Game|贪心算法
- [leetcode]55. Jump Game ,C++/PYTHON实现,medium难度
- leetcode 55. Jump Game [贪心]
- 55. Jump Game (leetcode)
- 【LeetCode】55. Jump Game
- Leetcode(W6):55. Jump Game
- Leetcode 55. Jump Game (Medium) (java)
- 【LeetCode】55. Jump Game
- [LeetCode] 55. Jump Game 解题思路
- 【LeetCode】55. Jump Game (Medium)
- LeetCode 55. Jump Game and 45. Jump Game II 题解
- leetcode55. Jump Game (贪心)
- LeetCode解题报告 55. Jump Game [medium]
- LeetCode | 55. Jump Game循环技巧题