LeetCode 45/55. Jump Game i, ii

1. 题目要求

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

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

Note:
You can assume that you can always reach the last index.

2. 解题思路

拿到这道题目, 我们想到的是 应该最大化 从当前节点出发, 走两个步骤可以走到的最大距离, 并以此来确定此处应该走的距离,

LeetCode 45/55. Jump Game i, ii_第1张图片
而这里所需要求的最大的步数, 实际上就是统计循环的次数~~

3. code

3.1 55

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int id = 0;
        while (id < nums.size() - 1){
            if (nums[id] == 0)
                return false;

            int max_id = id;
            int max_incr = 0;
            for (int i = 1; i != nums[id] + 1; i++){
                if (id + i < nums.size()){
                    if (nums[id + i] + id + i > max_id){
                        max_id = nums[id + i] + id + i;
                        max_incr = i;
                    }
                }
            }
            id = id + max_incr;
        }
        return true;
    }
};

3.2 45

class Solution {
public:
    int jump(vector<int>& nums) {
        int id = 0;
        int count = 0;
        while (id < nums.size() - 1){
            //if (nums[id] == 0)
            // return false;

            int max_id = id;
            int max_incr = 0;
            for (int i = 1; i != nums[id] + 1; i++){
                if (id + i >= nums.size() - 1){
                    return count + 1;
                }

                else{
                    if (nums[id + i] + id + i > max_id){
                        max_id = nums[id + i] + id + i;
                        max_incr = i;
                    }
                }
            }
            //id = ((max_incr == 0) ? max_id : id + max_incr);
            id = id + max_incr;
            count++;
        }
        return count;
    }
};

4. 大神解法

4.1 55

使用贪心算法, 每次迭代更新最远能够到达的距离

//I just iterate and update the maximal index that I can reach

bool canJump(int A[], int n) {
    int i = 0;
    for (int reach = 0; i < n && i <= reach; ++i)
        reach = max(i + A[i], reach);
    return i == n;
}

你可能感兴趣的:(LeetCode)