码迷,mamicode.com
首页 > 其他好文 > 详细

19.2.8 [LeetCode 55] Jump Game

时间:2019-02-08 18:35:11      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:one   display   integer   ssi   leetcode   pos   ext   alt   first   

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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.
技术图片
 1 class Solution {
 2 public:
 3     bool canJump(vector<int>& nums) {
 4         if (nums.size() == 1)return true;
 5         int reach = nums[0], prereach = 0, n = nums.size();
 6         while (1) {
 7             int nextreach = reach;
 8             bool flag = false;
 9             for (int i = prereach + 1; i <= reach && i < n; i++) {
10                 if (i + nums[i] > nextreach) {
11                     nextreach = i + nums[i];
12                     flag = true;
13                 }
14             }
15             if (nextreach >= n - 1)
16                 return true;
17             if (!flag)return false;
18             prereach = reach;
19             reach = nextreach;
20         }
21         return false;
22     }
23 };
View Code

指路→JUMP GAME II

19.2.8 [LeetCode 55] Jump Game

标签:one   display   integer   ssi   leetcode   pos   ext   alt   first   

原文地址:https://www.cnblogs.com/yalphait/p/10356443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!