LeetCode-M-Jump Game

題意

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.

Subscribe to see which companies asked this question.

Show Tags

解法

貪心解法:

  • 在每個點記錄當前可以到達的最大距離reach
  • 如果 i > reach,說明到達不了這個點,false

實現

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

    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章