程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetCode 55.Jump Game(跳躍游戲) 解題思路和方法

leetCode 55.Jump Game(跳躍游戲) 解題思路和方法

編輯:C++入門知識

leetCode 55.Jump Game(跳躍游戲) 解題思路和方法


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.


思路:這題相比於jump Game II多了0的填充,有可能是無法到達最終點的。代碼運用貪心思想,當無論怎麼走只能走到0的時候返回false。 具體代碼如下:
public class Solution {
    public boolean canJump(int[] nums) {
        if(nums.length == 0)
            return false;
        int i = 0;
        //判斷有沒有0,沒有0的肯定能達到
        while(i < nums.length){
            if(nums[i] == 0){
                break;
            }
            i++;
        }
        //沒有0,肯定能達到
        if(i == nums.length){
            return true;
        }
        i = 0;
        while(i < nums.length){
            if(i + nums[i] >= nums.length - 1)
                return true;
            if(nums[i] == 0)
                return false;
            int max = 0;
            int index = 0;
            //下一步能前進最大的步驟
            for(int j = i+1; j - i <= nums[i]; j++){
                if(max < j - i + nums[j]){
                    max = j - i + nums[j];
                    index = j;
                }
            }//走到下一步的索引
            i = index;
        }
        return true;
    }
}


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved