bool canJump(vector<int>& nums) {
    int reach = nums[0];
    for (int i = 1; i < nums.size() && reach >= i; i++)
    {
        if (i + nums[i] > reach)
        {
            reach = i + nums[i];  //贪心策略
        }
    }
    return reach >= (nums.size() - 1) ? true : false;
}

这是贪心算法类型的题目。

补充一个python的实现:

 1 class Solution:    
 2     def canJump(self, nums: 'List[int]') -> 'bool':
 3         n = len(nums)
 4         if n == 1:
 5             return True
 6         i = n - 1
 7         j = i - 1
 8         nexti = i
 9         while i>= 0:
10             tag = False
11             while j >= 0:
12                 diff = i - j
13                 val = nums[j]
14                 if diff <= val:
15                     nexti = j
16                     tag = True
17                 if tag:
18                     i = nexti
19                     j = i - 1
20                     break
21                 else:                    
22                     j -= 1
23             if not tag:
24                 return False
25             if nexti == 0:
26                 return True
27         return True

 

补充一个双指针思路的解决方案,使用python实现:

 1 class Solution:
 2     def canJump(self, nums: 'List[int]') -> bool:
 3         n = len(nums)
 4         j = 0#可以跳到的最远的索引
 5         for i in range(n):
 6             if i > j:#说明有无法跳跃的索引
 7                 return False
 8             j = max(j,i+nums[i])#更新最远的索引
 9         if j >= n - 1:#达到最右索引
10             return True
11         return False

 

posted on 2018-09-23 19:07  Sempron2800+  阅读(148)  评论(0编辑  收藏  举报