[LeetCode] 55. Jump Game

来源:互联网 发布:点云数据英文 编辑:程序博客网 时间:2024/06/05 15:59

【原题】
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.

【解释】
给定一个非负的数组,每一个数值表示可以跳跃的最大步数,问是否能到达数组的最后一个元素

【解题思路】
每次看最大能够到达的位置,若该位置能够到达最后一个元素,则返回ture,否则返回false

 public static boolean canJump(int[] nums) {            int maxIndex=0;                for(int i=0;i<nums.length&&i <= maxIndex;i++){                    maxIndex=Math.max(maxIndex, nums[i]+i);                }                          return (maxIndex>=nums.length-1);        }

注意:循环条件的i<=maxIndex,即在中间任何一个位置不可达都要结束循环。如果不加这个条件,则如:[3,2,1,0,4]就会返回true。

也可以采用逆向思维,见这里:

  public boolean canJump(int[] A) {          int last = A.length - 1;          for (int i = A.length - 2; i >= 0; i--) {              if (i + A[i] >= last) {                  last = i;              }          }          return (last <= 0);      }
原创粉丝点击