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.
Subscribe to see which companies asked this question
这个题的意思是跳棋游戏,就是给你一组正整数,每一个代表能往后跳多少个位置。
如果从第一个跳到最后那个数,就返回成功否则返回失败。
比如说[1,0],从第一个能往后跳1个,到了最后一个不管最后一个是多少,反正就是True
再说[0 ,1],从第一个只能往后跳0个,也就是跳不到,返回false
怎么做呢,用贪心算法。
意思是说:不管每一步怎么跳,我都跳到最后,跳到不能跳为止。
比如我们用一个变量G,来记录我能跳到的最后的位置。对第i步来说,从第i个位置出发的最远是nums[i]+inums[i]+i那么我们的G=max(G,nums[i]+i)G=max(G,nums[i]+i)
如果在某一步i>G,也就是说,前面能跳到的最远距离跳不到i,那就肯定失败。
如果最终能跳到最后一步就返回成功。
代码如下:
C++
class Solution {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
if (!len)return false;
int G = nums[0];
for(int i =1; i!=len;i++){
if(G<i)return false;
G = max(G,nums[i]+i);
if(G>=len-1)return true;
}
return G>=len-1;
}
};
python
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
L = len(nums)
if L==0:
return False
G = nums[0]
for i in range(1,L):
if G<i:
return False
G=max(G, nums[i]+i)
if G>=L-1:
return True
return G>=L-1