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[i]代表的是从i能够跳出的最大步数,而不是从i只能跳出A[i]步。

    用一个boolean型的数组记录某个位置能够到达。在位置i时,遍历所有的位置j(j<i),如果能够到达j而且能够从j跳到i,那么最终就可以到达i。

    代码如下:

     1 public class Solution {
     2     public boolean canJump(int[] A) {
     3         if(A == null || A.length == 0)
     4             return true;
     5         
     6         boolean[] reach = new boolean[A.length];
     7         reach[0] = true;
     8         
     9         for(int i = 1;i < A.length;i++){
    10             for(int j = 0;j < i;j++){
    11                 if(reach[j] && j+A[j]>=i){ 
    12                     reach[i] = true;
    13                     break;
    14                 }
    15             }
    16         }
    17         
    18         return reach[A.length-1];
    19     }
    20 }
  • 相关阅读:
    通过另外一个应用程序给多个文本框赋值, 模拟单击事件
    AngularJS
    九章算法
    实现继承
    二分查找
    NET Core依赖注入解读&使用Autofac替代实现
    NET SignalR 与 LayIM2.0
    WebVR
    依赖注入
    如何实现配置与源文件的同步
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3858719.html
Copyright © 2011-2022 走看看