[LeetCode]Jump Game
Posted skycore
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]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
.
解题思路:
贪心思路,当当前maxStep == 0时, 返回false,如果当前位置加上maxStep>数组长度,返回false
1 class Solution { 2 public: 3 bool canJump(vector<int>& nums) { 4 if (nums.size() == 0 || nums.size() == 1) { 5 return true; 6 } 7 8 int maxStep = nums[0]; 9 10 for (int i = 1; i < nums.size(); ++i) { 11 if (maxStep == 0) { 12 return false; 13 } 14 15 maxStep -= 1; 16 if (maxStep < nums[i]) { 17 maxStep = nums[i]; 18 } 19 20 if (i + maxStep >= nums.size() - 1) { 21 return true; 22 } 23 } 24 25 return true; 26 } 27 };
以上是关于[LeetCode]Jump Game的主要内容,如果未能解决你的问题,请参考以下文章