Leetcode45. Jump Game II

題目

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Note:
You can assume that you can always reach the last index.

思路

使用廣度遍歷,每走一步,遍歷可以走的所有路徑

測試案例

[]
[1,2,3,4,5]
[1,1,1,1,1,1,1,1]
[1]

代碼

package leetcodeArray;

public class Leetcode45JumpGameII {
    public int jump(int[] nums) {
        int i = 0, j = 1, steps = 0, n = nums.length;

        while(j < n){
            int endj = Math.min(nums[i] + i + 1, n);
            while(j < endj){
                if(nums[j] + j > nums[i] + i ) i = j;
                j++;
            }
            System.out.println(endj);
            steps++;
        }
        return steps;
    }
}

運行結果

這裏寫圖片描述

他山之玉

int jump(int A[], int n) {
     if(n<2)return 0;
     int level=0,currentMax=0,i=0,nextMax=0;

     while(currentMax-i+1>0){       //nodes count of current level>0
         level++;
         for(;i<=currentMax;i++){   //traverse current level , and update the max reach of next level
            nextMax=max(nextMax,A[i]+i);
            if(nextMax>=n-1)return level;   // if last element is in level+1,  then the min jump=level 
         }
         currentMax=nextMax;
     }
     return 0;
 }
class Solution {
public:
    int jump(int A[], int n) {
        vector<int> track(n, 0);

        for(int i=1; i<n; i++){
            int min = INT_MAX;
            for(int j=0; j<i; j++){
                if(track[j] < min && A[j]+j >= i)
                    min = track[j];
            }
            track[i] = min+1;
        }
        return track[n-1];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章