Leetcode 55. Jump Game

来源:互联网 发布:宏观研究知乎 编辑:程序博客网 时间:2024/06/06 02:59

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.

class Solution {public:    bool canJump(vector<int>& nums) {        size_t maxPos = nums[0];        size_t start = 1;        while (maxPos < nums.size() - 1) {            size_t tmpMax = maxPos;            for (size_t i = start; i <= maxPos; ++i) {                tmpMax = max(nums[i] + i, tmpMax);            }            // 遇到 0 无法前进            if (tmpMax == maxPos) break;            start = maxPos + 1;            maxPos = tmpMax;        }        if (maxPos < nums.size() - 1)            return false;        return true;    }};

参考后
其实思路一样, 人家的代码堪称惊艳

class Solution {public:    bool canJump(vector<int>& nums) {          size_t size = nums.size();        size_t maxPos = nums[0];        size_t i = 0;        for (size_t reach = nums[0]; i < size && i <= reach; ++i) {            reach = max(reach, i + nums[i]);        }        return i == size;    }};
原创粉丝点击