zoukankan      html  css  js  c++  java
  • Jump Game —— LeetCode

    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.

    题目大意:给定一个非负数组,每个元素代表可以跳的步数,判断从第一个能否跳到最后一个。

    解题思路:暴力?二重循环,检查是否能到达最后一个元素。

         优化:时间O(n),空间O(1),一次遍历,首先记录当前可以覆盖的最大下标,遍历的时候如果从当前位置可以跳的更远则更新最大下标,如果当前位置不在最大下标覆盖范围内则return false,如果最大下标比数组更长,则return true。

    public class Solution {
        public boolean canJump(int[] nums) {
            if(nums == null){
                return false;
            }
            int pos = 0;
            for(int i=0;i<nums.length;i++){
                if(pos>=nums.length-1){
                    return true;
                }
                if(i<=pos){
                    if(i+nums[i]>pos)
                        pos= i +nums[i];    
                }
                else{
                    return false;
                }
            }
            return false;
        }
    }
  • 相关阅读:
    从输入url到浏览器加载过程(回答此问题的一个主干脉络)
    如何减少回流,重绘
    mac常用启动各种服务的命令
    分布式笔记搬迁
    JAVA基础
    EasyExcel引入
    mac 好用软件地址存储
    2018/4/11
    2018/04/04
    jdk各版本
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4514119.html
Copyright © 2011-2022 走看看