zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    Example 1:

    Input: nums = [2,3,1,1,4]
    Output: true
    Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
    

    Example 2:

    Input: nums = [3,2,1,0,4]
    Output: false
    Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

    Constraints:

    • 1 <= nums.length <= 3 * 10^4
    • 0 <= nums[i][j] <= 10^5

    跳跃游戏。题意是给一个非负整数数组,数字代表你在该位置可以跳跃的最大长度(注意:你不一定需要跳这么远),你的起点是在数组的第一个位置。判断你是否能跳跃到数组的最后一个位置。

    这题有别的解法但是我这里给出的是贪心的思路。设一个变量K,表示从起点开始最远可以跳几步,初始化K = 0。遍历数组的时候,一旦发现i > k就说明i点的坐标是无法达到的,返回false;更新K的方式是i + nums[i],表示在i位置最远可以跳到什么位置。

    时间O(n)

    空间O(1)

    JavaScript实现

     1 /**
     2  * @param {number[]} nums
     3  * @return {boolean}
     4  */
     5 var canJump = function (nums) {
     6     let k = 0;
     7     for (let i = 0; i < nums.length; i++) {
     8         if (i > k) return false;
     9         k = Math.max(k, i + nums[i]);
    10     }
    11     return true;
    12 };

    Java实现

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

    LeetCode 题目总结

  • 相关阅读:
    Android网络开发的那些事儿
    first day to Ruby on rails
    [转]Windows SDK与DirectX SDK集成
    Windows8
    [转]MPI--MPI+VS2010 配置及编译
    codeblock添加头文件路径和静态库路径
    汇编笔记1:debug
    Eclipse Error
    Android SDk 离线安装方法
    求一程序员合租,回龙观东大街地铁站十分钟,精装次卧2000,无需押金,一共两家
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12409680.html
Copyright © 2011-2022 走看看