zoukankan      html  css  js  c++  java
  • [LeetCode] Jump Game

    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 };
  • 相关阅读:
    mysql创建表
    MySql数据类型(转)
    mysql命令总结
    php文件遍历类:FileBianli.class.php
    php文件删除
    php文件复制
    php文件遍历
    php下载c
    智能眼镜的行业应用
    《代谢增长论》读书笔记
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4649395.html
Copyright © 2011-2022 走看看