码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Jump Game

时间:2015-07-15 20:57:01      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

This problem has a very concise solution in this link, just 4-lines. The code is rewritten below.

1 class Solution {
2 public:
3     bool canJump(vector<int>& nums) {
4         int i = 0, n = nums.size();
5         for (int r = 0; i < n && i <= r; i++)
6             r = max(r, i + nums[i]);
7         return i == n;
8     }
9 };

The above code can be further optimized by avoiding unnecessary checks. Once we are able to reach the last position, we are already done.

1 class Solution {
2 public:
3     bool canJump(vector<int>& nums) {
4         int i = 0, r = 0, n = nums.size();
5         for (; i < n && i <= r && r < n - 1; i++)
6             r = max(r, i + nums[i]);
7         return r >= n - 1;
8     }
9 };

Or we can rewrite the code a bit longer to make the idea obvious.

 1 class Solution {
 2 public:
 3     bool canJump(int A[], int n) {
 4         int start = 0, end = 0;
 5         while(start <= end && end < n - 1) { 
 6             end = max(end, start + A[start]);
 7             start++;
 8         }
 9         return end >= n - 1;
10     }
11 };

 

[LeetCode] Jump Game

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4649395.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!