LeetCode 55. Jump Game

来源:互联网 发布:轻小说软件 编辑:程序博客网 时间:2024/06/11 03:52

Description

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.

Analysis

贪心算法。
在位置i处考虑从此处能到达的最远位置(显然最远位置能够达到,那么中途任何一个位置都可达到)。遍历后若发现最远位置等于或超过最后一个位置,这说明一定存在一种方法到达最后一个位置。
不加证明地说,这样规划也可以得到最少跳数的路径。

Code

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

Appendix

  • Link: https://leetcode.com/problems/jump-game/
  • Run Time: 19ms