Friday, February 20, 2015

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.
------------------------- thinking --------------------------------------------
1. bug: when is the time to return true? I only checked biggest when biggest is updated, but for case [0], the biggest will not be updated, but it still needs to return true

----------------------------- codes -------------------------------------------
class Solution {
public:
    bool canJump(int A[], int n) {
        int biggest = 0;
        for(int i = 0; i < n; i++) {
            if (i > biggest) {
                return false;
            }
            if (i + A[i] > biggest) {
                biggest = i + A[i];
                //bug here              
                //if (biggest >= n - 1) {
                    //return true;
                //}              
            }
            if (biggest >= n - 1) {
                return true;
            }
        }
        return false;
    }
};

No comments:

Post a Comment