• leetcode55


    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
  • 相关阅读:
    [Luogu1126] 机器人搬重物
    [POJ1830] 开关问题
    [bzoj3139] 比赛
    [POJ3349] Snowflake Snow Snowflakes
    The Tour
    [POJ3740] Easy Finding
    [vijos1453] 曼哈顿距离
    [POJ1632] Vase collection
    Codewars笔记
    Appium知识积累
  • 原文地址:https://www.cnblogs.com/asenyang/p/9693478.html
Copyright © 2020-2023  润新知