2014年11月30日星期日

[Leetcode] Jump Game I & 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.
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.

We keep a right boundary represent the maximum index we could reach, when we sweep to the maximum index, we update this right boundary accordingly, whenever the right boundary gets to the last index, we know that we could get there, however, when we have reach the right boundary but we still not get the last index, we know that we could not reach the last index. The idea is some what like Breadth First Search.

    public boolean canJump(int[] A) {
        int n = A.length;
        if(n == 1)
            return true; // corner case
        int ma = 0;
        for(int i = 0; i <= ma; i++) {
            ma = Math.max(ma, i+A[i]); // extend the right boundary
            if(ma >= n-1)
                return true;
        }
        return false;
    }

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

We use the similar idea of the above solution, this time we keep a window indicate the start position and end position, we sweep this window, and update the next step's end position and set next step's start position as end+1. Only when end position is not less than start position can we continue to jump, otherwise we have reach the maximum index we could reach. Once the end position where we could get exceeds the last index. We return the current step. This is just what Breadth First Search does.

    public int jump(int[] A) {
        int n = A.length;
        if(n == 1)
            return 0; // corner case
        int start = 0, end = 0;
        int nextS = end+1, nextE = end;
        int cnt = 1;
        while(nextE < n) {
            for(int i = start; i <= end; i++) { // according to the current step to update the next step where we could get
                nextE = Math.max(nextE, i+A[i]);
                if(nextE >= n - 1)
                    return cnt;
            }
            if(nextE < nextS) 
                break; // we could not continue to extend the boundary, this indicate that we could not reach the end
            start = nextS;
            end = nextE;
            nextS = end + 1;
            cnt++;
        }
        return cnt;
    }

没有评论:

发表评论