首页 > 其他 > 详细

45. Jump Game II

时间:2018-07-01 19:23:06      阅读:192      评论:0      收藏:0      [点我收藏+]

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.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

从起点跳到终点,求最小的跳跃次数,在 i 处能跳的最远距离是 nums[i]。

 

假如当前位于 i ,能跳跃的最大距离是 nums[i],对于每一个 j ∈ [i + 1, i + nums[i] ],通过这个点能达到的最远距离是 j + nums[j] 。那么最佳跳板就是 j 

 1 class Solution {
 2 public:
 3     int jump(vector<int>& nums) {
 4         int i = 0;
 5         int cnt = 0;
 6         int len = nums.size();
 7         while (i < len - 1) {
 8             if (i + nums[i] >= len - 1)
 9                 return cnt + 1;
10             int key = i + 1;
11             for (int j = i + 2; j <= i + nums[i]; ++j) {
12                 if (j + nums[j] > key + nums[key])
13                     key = j;
14             }
15             i = key;
16             ++cnt;
17         }
18         return cnt;
19     }
20 };

 

45. Jump Game II

原文:https://www.cnblogs.com/Zzz-y/p/9250961.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!