LeetCode_Array_55. Jump Game (C++)

目录

1,题目描述

2,解题思路

3,代码【C++】

4,运行结果


1,题目描述

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.

Example 1:

Input: [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: [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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2,解题思路

参考了这位大神的思路(tql,代码简洁效率高!!!),原文请见@Ikaruga 【跳跃游戏】别想那么多,就挨着跳吧

  • 设置最远跳跃点maxPoint;
  • 若当前位置i 大于maxPoint,说明此位置无法到达,返回false;
  • 将maxPoint与当前位置可到达的最远点比较,取最大值更新maxPoint;
  • 若maxPoint已大于等于last index,返回true;
  • 若循环全部结束仍返回true;

3,代码【C++】

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int maxPoint = 0;                         //更新可到达的最远位置
        for(int i = 0 ; i < nums.size() ; i++){
            if(i > maxPoint) return false;        //即当前位置i无法到达
            maxPoint = max(maxPoint,i + nums[i]);
            if(maxPoint >= nums.size() - 1) return true;
        }
        return true;
    }
};

4,运行结果

发布了45 篇原创文章 · 获赞 5 · 访问量 2211

猜你喜欢

转载自blog.csdn.net/qq_41528502/article/details/104065673