第十五周:55. Jump Game

    xiaoxiao2021-03-25  67

    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.

    思路就是用一个值distance与当前第i个值的A[I] + I比较大小,记录下最大值。如果一次循环完了,最大值大于数组的长度,那么证明可以到达,否则不能到达。

    AC:

    class Solution { public: bool canJump(vector<int>& nums) { int distance = 0; int n=nums.size(); for(int i = 0;i < n && i <= distance;++i){ distance = max(nums[i]+i,distance); } if(distance < n-1){ return false; } return true; } };

    转载请注明原文地址: https://ju.6miu.com/read-37730.html

    最新回复(0)