[LeetCode] Jump Game 数组控制
2014-11-28 05:47
441 查看
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.
Determine if you are able to reach the last index.
For example:
A =
A =
Hide Tags
Array Greedy
题目很简单,思路如下:
创建一个标记为last,表示A数组下标为last 前的位置都可以达到,初始化为 1.
从左遍历数组,当前位置加上可跳跃的长度A[i] 更新last。
如果last >= n ,即可以达到数组末尾,否则失败。
我写的如下:
View Code
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A =
[2,3,1,1,4], return
true.
A =
[3,2,1,0,4], return
false.
Hide Tags
Array Greedy
题目很简单,思路如下:
创建一个标记为last,表示A数组下标为last 前的位置都可以达到,初始化为 1.
从左遍历数组,当前位置加上可跳跃的长度A[i] 更新last。
如果last >= n ,即可以达到数组末尾,否则失败。
我写的如下:
#include <iostream> using namespace std; /**class Solution { public: bool canJump(int A[], int n) { if(n<=1) return true; int last = 1; for(int i =0;i<last&&i<n;i++){ last = last>i+A[i]+1?last:i+A[i]+1; if(last>=n) return true; } return false; } }; */ class Solution { public: bool canJump(int A[], int n) { for(int i = n-2; i >= 0; i--){ if(A[i] == 0){ int j; for(j = i - 1; j >=0; j--){ if(A[j] > i - j) break; } if(j == -1) return false; } } return true; } }; int main() { int A[] = {3,2,1,1,4}; Solution sol; cout<<sol.canJump(A,sizeof(A)/sizeof(int))<<endl; return 0; }
View Code
相关文章推荐
- LeetCode--------55. Jump Game(数组中的数字跳跃)
- 一个包含指针数组的排序和使用函数指针来控制排序方式
- 使用这些Perl 函数控制数组和哈希
- 数组下标的灵活控制!!【实用】
- LeetCode Online Judge 题目C# 练习 - Jump Game
- java数组与内存的控制(1)
- 1. Java数组与内存控制
- 数组和内存控制
- java数组与内存控制
- Leetcode:Jump Game
- 字符串转成字符数组,同时控制输出字符数——ToCharArray、Response.Write新用法(2006-04-20 15:32)
- 流程控制和数组
- 疯狂讲义第四章 流程控制和数组
- LeetCode 题目之 数组两数之和问题
- 数组控制me("crlName")的调用方法
- 用指针控制数组范围
- PHP - Manual手册 - 语言参考 - 控制结构 - foreach遍历数组
- 使用这些Perl 函数控制数组和哈希
- Java数组与内存控制
- LeetCode: Jump Game