Sunday, November 23, 2014

[LeetCode] Jump Game I, II

Jump Game I

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.

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

思路:Jump Game I

注意题目中A[i]表示的是在位置i,“最大”的跳跃距离,而并不是指在位置i只能跳A[i]的距离。所以当跳到位置i后,能达到的最大的距离至少是i+A[i]。用greedy来解,记录一个当前能达到的最远距离maxIndex:

1. 能跳到位置i的条件:i<=maxIndex。
2. 一旦跳到i,则maxIndex = max(maxIndex, i+A[i])。
3. 能跳到最后一个位置n-1的条件是:maxIndex >= n-1


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    bool canJump(int A[], int n) {
        int maxIndex = 0;
        for(int i=0; i<n; i++) {
            if(i>maxIndex || maxIndex>=(n-1)) break;
            maxIndex = max(maxIndex, i+A[i]);
        } 
        return maxIndex>=(n-1) ? true : false;
    }
};


思路:Jump Game II

同样可以用greedy解决。与I不同的是,求的不是对每个i,从A[0:i]能跳到的最远距离;而是计算跳了k次后能达到的最远距离,这里的通项公式为:

d[k] = max(i+A[i])     d[k-2] < i <= d[k-1]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    int jump(int A[], int n) {
        int curMax = 0, njumps = 0, i = 0;
        while(curMax<n-1) {
            int lastMax = curMax;
            for(; i<=lastMax; i++) 
                curMax = max(curMax,i+A[i]);
            njumps++;
            if(lastMax == curMax) return -1;
        }
        return njumps;
    }
};

1 comment:

  1. my jump game solution using backward or forward:
    class Solution:
    # @param {integer[]} nums
    # @return {boolean}
    def canJump(self, nums):
    n = len(nums)
    last = n-1
    for i in range(2,n+1):
    if n-i + nums[-i] >= last:
    last = n-i
    return last == 0

    class Solution:
    # @param {integer[]} nums
    # @return {boolean}
    def canJump(self, nums):
    reachable = 0
    for i in range(len(nums)):
    if i > reachable: return False
    reachable = max(reachable, i+nums[i])
    return True

    URL: http://traceformula.blogspot.com/2015/08/jump-game.html

    ReplyDelete