1. 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], returntrue.

A =[3,2,1,0,4], returnfalse.

public class Solution {
    public boolean canJump(int[] nums) {

        if(nums.length == 0)    return true;

        int maxJump = nums[0];

        for(int i = 0; i < nums.length ; i ++){

            if(i > maxJump) return false;
            maxJump = Math.max(maxJump, nums[i] + i);
        }

        return true;
    }
}

2. 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 is2. (Jump1step from index 0 to 1, then3steps to the last index.)

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

public class Solution {
    public int jump(int[] nums) {

        if(nums.length == 0) return 0;

        int end     = 0;
        int maxJump = 0;
        int count   = 0;

        for(int i = 0; i < nums.length - 1; i ++){

            maxJump = Math.max(nums[i] + i, maxJump);
            if(i == end){
                end = maxJump;
                count ++;
                if(end >= nums.length - 1) break;
            }

        }

        return count;
    }
}

results matching ""

    No results matching ""