[leetcode]Jump Game I II

来源:互联网 发布:天刀捏脸详细数据 编辑:程序博客网 时间:2024/05/01 01:50

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.

解题思路:依次计算每个元素所能跳跃的最大步数,判断所跳跃的步数是否可以达到数组最后的元素,

如果最大跳跃距离等于当前元素所在位置,则表明本元素值为0,且跳跃会在此元素终止前进。

    bool canJump(int A[], int n) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if(n <= 1) return true;        int i = 0;        int e = 0;        while(true){            e = max(e, A[i] + i);            if(e >= n - 1) return true; //跳跃被阻塞            if(e == i) break;            i++;        }        if(e >= n - 1) return true;        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.)

此方法有借鉴
    int jump(int A[], int n) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        // 贪心算法的应用        int i = 0, tmp = 0, maxx = 0, sum = 0;        while(i < n){            if(tmp >= n - 1) break; //如果到达数组尾break            while(i <= tmp){//当前元素所能到达的最远处                maxx = max(maxx, i + A[i]);//记录在当前范围内某元素所能达到的最远处                i++;            }            tmp = maxx;//步数加1            sum++;        }        return sum;    }




0 0