zoukankan      html  css  js  c++  java
  • leetcode 之Jump Game

    题目描述:

    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. 

    即, 给定一组非负数, 每一个数字代表可以向后走的最大步数, 如A= [2, 3, 1, 1, 4], A[0] = 2, 代表从A[0]可以访问到(A[1] = 3, A[2] =1), 同理,类推。

    如果从第一个数开始, 按上述方法, 可以访问到最后一个数, 则该数组返回True, 否则返回False。

    思路:

    对于数字可访问的区间,我们记录并更新最大可访问的index
    如 A[0] = 2, 可访问的区间为(0, 1, 2),最大访问的index = 2, 接下来访问该区间内的下一个数字,A[1] = 3, 则A[1] 可访问的区间为 (1, 2, 3, 4),
    最大访问index 更新为4,4 已经是数组的最后一个元素了,则返回True, 否则继续遍历。 更新最大访问的index

    代码如下:

    class Solution(object):
        def canJump(self, nums):
            """
            :type nums: List[int]
            :rtype: bool
            """
            l = len(nums)
            if l == 0 or l == 1:
                return True
            step = nums[0] + 0
            if step >= l-1:
                return True
            i = 1
            while i < step+1:
                maxStep = nums[i] + i  #当前数字可访问的最大index
                if maxStep >= l-1:
                    return True
                step = max(maxStep, step)
                i = i + 1
            return False
    ~~~~~
  • 相关阅读:
    CentOS进程资源占用高原因分析命令
    Centos下修改启动项和网络配置
    CentOS查看系统信息命令和方法
    [vim]设置vim语法高亮显示和自动缩进
    [vim]vim中有中文乱码
    setState回调
    服务器安装nginx
    小程序map
    后台合成图片
    阿里云服务器添加nginx
  • 原文地址:https://www.cnblogs.com/missmzt/p/5709876.html
Copyright © 2011-2022 走看看