Sunday, May 3, 2015

[LeetCode] 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.
Solution: Greedy. Maintain the current max reach, and update it as necessary.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Solution {
    public boolean canJump(int[] nums) {
        int maxDist = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i <= maxDist) {
                maxDist = Math.max(i + nums[i], maxDist);
            }
        }
        return (maxDist >= nums.length - 1);
    }
}
Another version. We update a batch this time.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Solution {
    public boolean canJump(int[] nums) {
        if (nums.length <= 1) {
            return true;
        }
        int maxDist = 0;
        int i = 0;
        while (i < nums.length && i <= maxDist) {
            for (int j = i; j <= i + nums[i] && j < nums.length; j++) {
                maxDist = Math.max(maxDist, j + nums[j]);
            }
            i = Math.max(i + nums[i], i + 1);
        }
        return (maxDist >= nums.length - 1);
    }
}

No comments:

Post a Comment