面试经典150题——Day9

文章目录

    • 一、题目
    • 二、题解

一、题目

55. Jump Game

You are given an integer array nums. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Example 1:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

Constraints:

1 <= nums.length <= 104
0 <= nums[i] <= 105

题目来源:leetcode

二、题解

1.最初的解法

class Solution {
public:
    const int N = 10010;
    int max(int a,int b){
        if(a > b) return a;
        else return b;
    }
    bool canJump(vector<int>& nums) {
        int n = nums.size();
        bool dp[N];
        int maxDistance = 0;
        for(int i = 0;i < n;i++){
            //可达时,重新计算最远距离
            if(maxDistance >= i){
                maxDistance = max(maxDistance,i + nums[i]);
            }
            if(maxDistance >= i) dp[i] = true;
            else dp[i] = false;
        }
        return dp[n-1];
    }
};

2.优化后的解法

不需要一个数组专门存储

class Solution {
public:
    int max(int a,int b){
        if(a > b) return a;
        else return b;
    }
    bool canJump(vector<int>& nums) {
        int n = nums.size();
        int maxDistance = 0;
        int canReach = false;
        for(int i = 0;i < n;i++){
            //可达时,重新计算最远距离
            if(maxDistance >= i){
                maxDistance = max(maxDistance,i + nums[i]);
            }
            if(maxDistance >= i) canReach = true;
            else canReach = false;
        }
        return canReach;
    }
};

你可能感兴趣的:(面试,算法,数据结构)