The Solution to Leetcode 55 Jump Game

来源:互联网 发布:服务器的80端口是什么 编辑:程序博客网 时间:2024/06/03 15:04

Question:

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.

思路:当数组除最后一个元素中出现0的时候,则不能跳到最后一个元素,返回false。

元素的数值加上该元素的下标是跳转到下一个元素的下标。我理解的题目的意思是最终正好跳到最后一个元素,但是leetcode 给的expected answer是跳到大于或等于最后一个元素的索引即可,所以代码如下。

Answer:

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

run code results:
Your input
[2,3,1,1,4]
Your answer
true
Expected answer
true


0 0