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.

 

bool canJump(int* nums, int numsSize) {
    int cur = 0;    //当前的下标
    int max = 0;    //下一个将到达的最大下标
    int tmp_max = 0;
    if (numsSize == 0)
        return true;
    max = nums[0];    //下一个最大的下标:nums[0] + cur
    while(max < numsSize - 1){
        for(int i = ++cur; i <= max; i++){    //当开始时,当前的下标就前进一格
            tmp_max = nums[i] + i;
            if(tmp_max >= numsSize)
                return true;
            if(tmp_max > max){    //备份最大值
                max = tmp_max;
                cur = i;
            }
        }
        if(max <= cur)    //如果下一个最大值不比当前的下标大,则说明再也前进不了了
            return false;
    }
    return true;
}
  • 使用贪心算法,每次得到最大值
  • 要分清楚每次循环中 i 代表了什么;而且每次都要保持这个含义
    • 不要一次是代表运行的次数另一次又代表下标
    • 如果是代表次数,可以按照常见的从0 到 < max;如果代表了下标最好是直接<= max;更容易理解
posted @ 2015-12-22 11:16  dylqt  阅读(185)  评论(0编辑  收藏  举报