zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    验证 Email
    取系统时间
    DbHelperSQL.cs
    显示BYTE流图片
    [原]c# 读取文本文件(txt)
    数据库文件组和文件的作用
    Transact—SQL
    m_pMainWnd
    sql server 2005 window 身份证验证模式与SQL Server身份验证
    WM_CLOSE WM_DESTROY WM_QUIT
  • 原文地址:https://www.cnblogs.com/asenyang/p/9693478.html
Copyright © 2011-2022 走看看