题目:

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

代码:

class Solution {
public:
int jump(vector<int>& nums) {
int max_jump=, next_max_jump=, min_step=;
for ( int i = ; i<=max_jump; ++i )
{
if ( max_jump>=nums.size()- ) break;
if ( max_jump < i+nums[i] ) next_max_jump = std::max(next_max_jump, i+nums[i]);
if ( i==max_jump )
{
max_jump = next_max_jump;
min_step++;
}
}
return min_step;
}
};

tips:

参考Jump Game的Greedy思路。

这道题要求求出所有可能到达路径中的最短步长,为了保持O(n)的解法继续用Greedy。

这道题的核心在于贪心维护两个变量:

max_jump:记录上一次跳跃能跳到最大的下标位置

next_max_jump:记录遍历所有max_jump之前的元素后,下一次可能跳到的最大下标位置

举例说明如下:

原始数组如右边所示:{7,0,9,6,9,6,1,7,9,0,1,2,9,0,3}

初始:max_jump=0 next_max_jump=0 min_step=1

i=0:next_max_jump=7  更新max_jump=7 更新min_step=1

i=1: 各个值不变

i=2: i+nums[i]=2+9=11>7 更新next_max_jump=11

i=3:i+nums[i]=3+6=9<11 不做更新

i=4: i+nums[i]=4+9=13>11 更新max_jump=13

...

i=7:i+nums[i]=7+7=14 >= nums.size()-1 返回min_step=2

完毕

==========================================

第二次过这道题,不太顺,大体复习了下思路。

class Solution {
public:
int jump(vector<int>& nums) {
if ( nums.size()== ) return ;
int ret = ;
int nextJump = ;
int maxLength = ;
for ( int i=; i<=maxLength; ++i )
{
if ( maxLength>=nums.size()- ) break;
nextJump = std::max(i+nums[i], nextJump);
if ( i==maxLength )
{
maxLength = nextJump;
ret++;
}
}
return ret;
}
};

==========================================

第三次过这道题,把代码改了一行,但是整体结构清晰了不少。

class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size()<) return ;
int steps = ;
int local = ;
int next = local;
for ( int i=; i<=local; ++i )
{
next = max(next, i+nums[i]);
if ( i==local )
{
steps++;
local = next;
if ( local>=nums.size()- ) return steps;
}
}
return ;
}
};

next只负责看下一跳能够到哪。

什么时候更新local了,再判断能否跳到尾部。

【Jump Game II 】cpp的更多相关文章

  1. 【Word Break II】cpp

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  2. 【Unique Paths II】cpp

    题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...

  3. 【Path Sum II】cpp

    题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...

  4. 【Spiral Matrix II】cpp

    题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...

  5. 【palindrome partitioning II】cpp

    题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...

  6. 【Combination Sum II 】cpp

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  7. 【Word Ladder II】cpp

    题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  8. 【Single Num II】cpp

    题目: Given an array of integers, every element appears three times except for one. Find that single o ...

  9. 【N-Quens II】cpp

    题目: Follow up for N-Queens problem. Now, instead outputting board configurations, return the total n ...

随机推荐

  1. C#对话框-打开和保存对话框(转)

    //打开文件            OpenFileDialog openFileDialog = new OpenFileDialog();            openFileDialog.In ...

  2. jQuery-名称符号$与其他库函数冲突

    1.通过全名替代简写的方式来使用 jQuery jQuery("button").click(function(){ jQuery("p").text(&quo ...

  3. 24个节点测试Linux VPS/服务器速度一键脚本使用 附服务器配置

    对于大部分网友而言,我们是希望购买的VPS.服务器既便宜也稳定,甚至还能提供更好的优质服务.这样的商家有没有呢?回答是基本没有.但是,只要我们购买的VPS在稳定性 和速度上对比同类的商家差不多,或者自 ...

  4. php生成纯数字、字母数字、图片、纯汉字的随机数验证码

    现在讲开始通过PHP生成各种验证码旅途,新手要开车了,请刷卡! 首先,我们开始先生成一个放验证码的背景图片 注:没有Imagejpg()这个函数,只有imagepng()函数 imagecreatet ...

  5. ffmpeg 资源[转]

    http://blog.csdn.net/leixiaohua1020/article/details/15811977 一. FFmpeg主站 1. FFmpeg的源码发布,资料 网址:   htt ...

  6. Redis多机数据库

    复制 PSYNC命令具有完整重同步(full resynchronization)和部分重同步(partial resynchronization)两种模式: ·其中完整重同步用于处理初次复制情况:完 ...

  7. python_34_文件操作3

    f=open('yesterday',encoding='utf-8') print(f.tell())#文件句柄所在指针指向的位置,即光标在哪里(按字符计数) f.readline()#读一行 pr ...

  8. Java基础面试操作题:读取该文件内容,并按照自然顺序排序后输出到 另一个文件中

    package com.swift; import java.io.FileInputStream; import java.io.FileNotFoundException; import java ...

  9. iOS 闭包传值 和 代理传值

    let vc = ViewController() let navc = UINavigationController(rootViewController: vc) window = UIWindo ...

  10. 散列表的ASL计算

    题目: 已知关键字序列为{30,25,72,38,8,17,59},设散列表表长为15.散列函数是H(key)=key MOD 13,处理冲突的方法为二次探测法Hi= ( H(key) + di )m ...