【leetcode】55. Jump Game 數組跳轉是否能夠到達末節點

1. 題目

Given an array of non-negative integers, you are initially positioned at the first index of the array.code

Each element in the array represents your maximum jump length at that position.element

Determine if you are able to reach the last index.it

For example:
A = [2,3,1,1,4], return true.io

A = [3,2,1,0,4], return false.ast

2. 思路

遍歷記錄下當前能到達的最遠的位置,若是能到達n,則必定能達到<n的任何位置
若是當前能到達的位置小於當前的下標,則說明走不下去了,提早中斷退出。
第一個點時起點,必定能夠達到,先加入進去。
遍歷完成以後,看能到達的位置是否覆蓋了末節點的位置。class

3. 代碼

耗時:12ms遍歷

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int overflow = 0; // 當前能夠覆蓋到的下標
        for (int i = 0; i < nums.size() - 1; i++) {
            if (overflow < i) { return false; }  // 提早中斷, 走不下去了
            int k = i + nums[i];
            if (k > overflow) { overflow = k; }
        }
        return overflow >= nums.size() - 1;
    }
};
相關文章
相關標籤/搜索