随笔- 509  文章- 0  评论- 151  阅读- 22万 

Jump Game II

2014.2.26 04:35

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.

For example:
Given array A = [2,3,1,1,4]

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.)

Solution:

  In this problem, we have to calculate the minimal number of steps to reach the last position. In Jump Game we recorded the furthest position reachable, while in this problem the last farthest position will be recorded as well. The reason for that, is whenever a new boundary is found, you'll have to go one step further to reach that boundary. We count the number of steps as we update the furthest position.

  The algorithm is still one-pass and online.

  Time complexity is O(n). Space complexity is O(1).

Accepted code:

复制代码
 1 // 1CE, 3WA, 1AC, online algorithm with O(n) time.
 2 class Solution {
 3 public:
 4     int jump(int A[], int n) {
 5         if (A == nullptr || n <= 0) {
 6             return -1;
 7         } else if (n == 1) {
 8             return 0;
 9         }
10         
11         int last_pos, this_pos;
12         int i;
13         int result;
14         
15         last_pos = 0;
16         this_pos = 0;
17         result = 0;
18         for (i = 0; this_pos < n - 1; ++i) {
19             if (i > this_pos) {
20                 return -1;
21             }
22             if (i + A[i] > this_pos) {
23                 if (i > last_pos) {
24                     last_pos = this_pos;
25                     ++result;
26                 }
27                 this_pos = i + A[i];
28             }
29         }
30         
31         return result + 1;
32     }
33 };
复制代码

 

 posted on   zhuli19901106  阅读(211)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示