55. Jump Game

题目:

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 = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

链接:https://leetcode.com/problems/jump-game/#/description

4/19/2017

8ms, 72%

早晨讨论的结果,注意第6,7行的判断。从前往后记录rightMost的位置,如果rightMost在最后一个位置或者超过,返回True,否则返回 false

 1 public class Solution {
 2     public boolean canJump(int[] nums) {
 3         int rightMost = 0;
 4         for (int i = 0; i < nums.length; i++) {
 5             if (i + nums[i] > rightMost) rightMost = i + nums[i];
 6             if (rightMost >= nums.length - 1) return true;
 7             if (rightMost == i) return false;
 8         }
 9         return false;
10     }
11 }

官方解法:

https://leetcode.com/articles/jump-game/

这种解法找的是从后往前最前面可以追到哪里,跟我写的正好相反。

 1 public class Solution {
 2     public boolean canJump(int[] nums) {
 3         int lastPos = nums.length - 1;
 4         for (int i = nums.length - 1; i >= 0; i--) {
 5             if (i + nums[i] >= lastPos) {
 6                 lastPos = i;
 7             }
 8         }
 9         return lastPos == 0;
10     }
11 }

其他人的算法,注意其for循环里面的判断,还有一个i <= reach

https://discuss.leetcode.com/topic/4911/linear-and-simple-solution-in-c

1 bool canJump(int A[], int n) {
2     int i = 0;
3     for (int reach = 0; i < n && i <= reach; ++i)
4         reach = max(i + A[i], reach);
5     return i == n;
6 }

更多讨论:

https://discuss.leetcode.com/category/63/jump-game

posted @ 2017-04-20 05:59  panini  阅读(144)  评论(0编辑  收藏  举报