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

Example:

Input:
 [2,3,1,1,4]

Output:
 2

Explanation:
 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.

Solution

(1) Java

class Solution {
    public int jump(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int step = 0;
        int range = 0;
        int farpoint = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i > range) {
                step++;
                range = farpoint;
            } 
            if (i == nums.length-1) {
                return step;
            }
            farpoint = Math.max(farpoint, i+nums[i]);
            if (farpoint >= nums.length-1) {
                return step+1;
            } 

        }
        return step;
    }
}

Simple code

public int jump(int[] A) {
    int jumps = 0, curEnd = 0, curFarthest = 0;
    for (int i = 0; i < A.length - 1; i++) {
        curFarthest = Math.max(curFarthest, i + A[i]);
        if (i == curEnd) {
            jumps++;
            curEnd = curFarthest;
        }
    }
    return jumps;
}

(2) Python

class Solution:
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        step, end, far = 0, 0, 0
        for i in range(len(nums)):
            if i > end:
                step += 1
                end = far
            if i == len(nums)-1:
                break
            far = max(far, i+nums[i])
            if far >= len(nums)-1:
                step += 1
                break
        return step

(3) Scala



results matching ""

    No results matching ""