LeetCode(55):ジャンプゲームJump Game(Java)


2019.5.28#プログラマー筆記試験必須#LeetCodeゼロブラシ個人メモ整理(継続更新)
知能問題である以上、暴力法は使えないに違いない.
1.行き先から
最大到達距離maxdistを格納する変数を設定し、移動後から各位置に移動するたびにこの距離を更新します.maxdistが最後のビットに到達できれば、ゲームは通過し、trueに戻る.到着できない場合はゲームに失敗しfalseに戻ります.
2.後ろから前へ
フラグビットが最後のlastPosを表し、後から新しい位置が末尾に到達するたびにlastPosがその位置に更新されるように設定します.lastPosがトップに到達できれば、ゲームは通過し、trueに戻る.到着できない場合はゲームに失敗しfalseに戻ります.
トランスミッションゲート:ジャンプゲーム
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.
非負の整数配列を指定すると、最初に配列の最初の位置に位置します.
配列内の各要素は、その位置でジャンプできる最大長を表します.
あなたが最後の位置に着くかどうかを判断します.
   1:
  : [2,3,1,1,4]
  : true
  :     0   1   1  ,     3          。

   2:
  : [3,2,1,0,4]
  : false
  :     ,         3    。             0 ,                 。

/**
 *
 * 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.
 *           ,             。
 *                         。
 *                。
 *
 */

public class JumpGame {

    //                 maxdist,                ,      。
    //   maxdist        ,     ,  true;      ,     ,  false。
    public boolean canJump(int[] nums) {
        int maxdist = 0;
        for(int i = 0; i <= maxdist; i++){
            int curdist = i + nums[i];
            if(curdist >= nums.length - 1) {
                return true;
            }
            maxdist = curdist > maxdist ? curdist : maxdist;
        }
        return false;
    }

    //              lastPos,                  ,  lastPos      。
    //   lastPos      ,     ,  true;      ,     ,  false。
    public boolean canJump2(int[] nums) {
        int lastPos = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i + nums[i] >= lastPos) {
                lastPos = i;
            }
        }
        return lastPos == 0;
    }
    
}



#Coding 1時間、Copying 1秒.いいねを残してくれてありがとう