【LeetCode】55. Jump Game
2017-01-08 10:30
519 查看
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 =
A =
Difficulty: Medium
贪心算法,思路是每一步确定能走的最大步数,如果中途出现最大步数为0的情况,则不能走到终点,如果中途出现最大步数大于当时的下标距离终点的距离,则可以到达
时间复杂度O(n)
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size()==0) return true;
//if(nums[0]==0) return false;
int max=-1;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>max) max=nums[i];
if(max >= nums.size()-i-1) return true;
if(max<=0) return false;
max--;
}
return false;
}
};
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.
Difficulty: Medium
贪心算法,思路是每一步确定能走的最大步数,如果中途出现最大步数为0的情况,则不能走到终点,如果中途出现最大步数大于当时的下标距离终点的距离,则可以到达
时间复杂度O(n)
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size()==0) return true;
//if(nums[0]==0) return false;
int max=-1;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>max) max=nums[i];
if(max >= nums.size()-i-1) return true;
if(max<=0) return false;
max--;
}
return false;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode刷题,没想到这么难搞!
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解