Jump Game II
2016-07-17 13:27
477 查看
题目描述:
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 =
The minimum number of jumps to reach the last index is
from index 0 to 1, then
Note:
You can assume that you can always reach the last index.
解题思路:
使用贪心法,假设当前位于数组的index i,那么下一跳选择的步数j需要满足:max(j+nums[i+j]) 其中j>=1 且j<=nums[i]
AC代码如下:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if (n <= 1) return 0;
int idx = 0;
int ans = 0;
while (idx < n){
if (idx == n - 1) return ans;
++ans;
if (idx + nums[idx] >= n - 1) return ans;
int step = nums[idx];
int local_max = 0;
int select_step = 0;
for (int j = 1; j <= step; ++j){
if (local_max < j + nums[idx + j]){
local_max = j + nums[idx + j];
select_step = j;
}
}
idx += select_step;
}
return ans;
}
};
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
1step
from index 0 to 1, then
3steps to the last index.)
Note:
You can assume that you can always reach the last index.
解题思路:
使用贪心法,假设当前位于数组的index i,那么下一跳选择的步数j需要满足:max(j+nums[i+j]) 其中j>=1 且j<=nums[i]
AC代码如下:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if (n <= 1) return 0;
int idx = 0;
int ans = 0;
while (idx < n){
if (idx == n - 1) return ans;
++ans;
if (idx + nums[idx] >= n - 1) return ans;
int step = nums[idx];
int local_max = 0;
int select_step = 0;
for (int j = 1; j <= step; ++j){
if (local_max < j + nums[idx + j]){
local_max = j + nums[idx + j];
select_step = j;
}
}
idx += select_step;
}
return ans;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解