博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - 45. Jump Game II
阅读量:7071 次
发布时间:2019-06-28

本文共 1808 字,大约阅读时间需要 6 分钟。

45. Jump Game II 

 ----------------------------------------------------------------------------

Mean: 

给定一个数组a,玩家的初始位置在idx=0,玩家需要到达的位置是idx=a.size()-1.

如果玩家在idx处,那么他最多可以向后走a[idx]步,问最少多少步可以走到终点.

analyse:

方法非常巧妙,类似于BFS.

Time complexity: O(N)

 

view code

/**
* -----------------------------------------------------------------
* Copyright (c) 2016 crazyacking.All rights steperved.
* -----------------------------------------------------------------
*       Author: crazyacking
*       Date  : 2016-03-08-14.52
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using
namespace
std;
typedef
long
long(
LL);
typedef
unsigned
long
long(
ULL);
const
double
eps(
1e-8);
class
Solution
{
public
:
   
int
jump(
vector
<
int
>&
nums)
   
{
       
int
i(
0
),
j(
1
),
steps(
0
), N(
nums
.
size());
       
while(
j
< N)
       
{
           
int
endj
=
min(
nums
[
i
]
+
i
, N);
           
while(
j
<
=
endj)
           
{
               
if(
nums
[
j
]
+
j
>
nums
[
i
]
+
i)
                   
i
=
j;
               
j
++;
           
}
           
steps
++;
       
}
       
return
steps;
   
}
};
// this is my TLE code :(
//class Solution
//{
//public:
//    int jump(vector<int>& nums)
//    {
//        queue<pair<int,int>> que; // pos,step
//        int res=INT_MAX;
//        que.push(make_pair(0,0));
//        while(!que.empty())
//        {
//            pair<int,int> top=que.front();
//            que.pop();
//            if(top.first>=nums.size()-1)
//                res=min(res,top.second);
//            for(int i=1;i<=nums[top.first] && i+top.first<=nums.size();++i)
//            {
//                que.push(make_pair(top.first+i,top.second+1));
//            }
//        }
//        return res;
//    }
//};
int
main()
{
   
int n;
   
while(
cin
>>n)
   
{
       
vector
<
int
>
ve;
       
for(
int
i
=
0;
i
<n;
++
i)
       
{
           
int
tempVal;
           
cin
>>
tempVal;
           
ve
.
push_back(
tempVal);
       
}
       
Solution
solution;
       
int
ans
=
solution
.
jump(
ve);
       
cout
<<
ans
<<
endl;
   
}
   
return
0;
}
/*
*/

转载地址:http://ysell.baihongyu.com/

你可能感兴趣的文章
Android学习笔记——Intents 和 Intent Filters(二)
查看>>
收藏的Android很好用的组件或者框架。
查看>>
SQL Server 数据库文件 4 点注意
查看>>
赛马题(转)
查看>>
网页的背景图片代码
查看>>
SURF算法与源码分析、下
查看>>
高速排序算法
查看>>
数学图形之伞形
查看>>
vs2008打包公布程序
查看>>
浅谈WebService的版本兼容性设计
查看>>
随便弄个名字 以后改
查看>>
opennebula auth module ldap
查看>>
使用Swift的代理,闭包来封装一个公用协议减少垃圾代码
查看>>
eclipse 使用jetty调试时,加依赖工程的源码调试方法
查看>>
自学MVC看这里——全网最全ASP.NET MVC 教程汇总(转)
查看>>
NETBEANS + XDEBUG + IIS PHP 代码 调试 DEBUG
查看>>
git log --pretty=format:" "
查看>>
js原生设计模式——12装饰者模式
查看>>
[转]JSON 入门指南
查看>>
Oracle错误——ORA-03113:在通信信道文件的末尾 解决方案
查看>>