zoukankan      html  css  js  c++  java
  • leetcode : 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.

    两种思路:

    第一种,动态规划

    第二种,贪心思路

    第一种:状态方程,  f[n] = true 如果  f[i] = true && nums[i] + i >= nums.length - 1 ,      0 <= i < n  

    f[n]表示能否从第一个数调到第n个数

    动态规划会超时: 因为n^2 时间复杂度 ,n的空间复杂度。

    第二种: 贪心思路。 一遍遍历过去,只要条件满足程序结束。

    用farthest指针指向当前能跳到的最远距离。 每次遍历时都进行更新,若返回条件,则推出。

    举例子:

    5,1,1,1,1,3,1,1,3.

    farthest 初值 = nums[0], 即farthest = 5;

    在遍历到蓝色的3(i = 5)时,此时nums[i] + i  = 5 + 3 = 8 > farthest, 更新farthest = 8.

    因为farthest >= nusm.length = 8 .直接结束。返回true。  

    public class Solution {
        public boolean canJump(int[] nums) {
         
         if(nums == null || nums.length == 0){
             return false;
         }   
         
         int farthest = nums[0];
         for(int i = 1; i < nums.length; i++){
             if(farthest >= i && nums[i] + i >= farthest ){
                 farthest = nums[i] + i;
                 if(farthest >= nums.length){
                     return true;
                 }
             }
         }
         
         return farthest >= nums.length - 1;
        }
    }
    

      

  • 相关阅读:
    算法学习(二)——树状数组求逆序数
    ZOJ 2412 Farm Irrigation
    排列的生成算法(一)
    汉诺塔递归实现
    汇编(五)
    汇编(四)
    汇编(三)
    汇编(二)
    0103MySQL中的B-tree索引 USINGWHERE和USING INDEX同时出现
    0103如何通过索引长度确定是否使用全索引
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6438871.html
Copyright © 2011-2022 走看看