Jump Game II, Leetcode 解题笔记

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.)

贪心算法,维护两个边界:[start, end],每次试着在这个范围内往前走能走到的最远的地方。

public class Solution {
    public int jump(int[] A) {
        if(A.length == 1) return 0;
        int start = 0;
        int end = 0;
        int step = 0;
        while(end < A.length){
            int furthest = 0;
            for(int i = start; i <= end; i++){
                if(i+A[i] >= A.length-1){
                    return step;
                if(i+A[i] > furthest){
                    furthest = i+A[i];
            start = end+1;
            end = furthest;
        return 0;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s