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

    题目:

    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.

    题意及分析:根据题目要求,数组里的每个元素表示从该位置可以跳出的最远距离,要求问从第一个元素(index=0)开始,能否达到数组的最后一个元素,这里认为最后一个元素为终点。这里是到达,说明超过也行,看下图能更好的理解题意。

    所以这里可以使用贪心算法,计算出某个点时 能够跳出的最大距离(当前的最大值和(当前点+能跳出的最大距离)的较大的值),如果能跳出的最大距离大于最后一个点的位置,那么返回true,能到达;如果到达当前点后,不能在往后跳,那么不能达到最后点,返回false。

    代码:

    public class Solution {
        public boolean canJump(int[] nums) {
             if(nums.length<1)
            	return false;
            if(nums.length==1)
            	return true;
            
            int max=0;		//记录到当前点时能到达的最大位置
            for(int i=0;i<nums.length-1;i++){
            	max=Math.max(max, i+nums[i]);
            	if(max<i+1){		//如果到达不了后续点(这里通常情况为 当前点为0,前面的能达到的最大点 为当前点或者当前点前面的点),返回false
            // 		System.out.println(false);
            		return false;
            	}
            	if(max>=(nums.length-1)){
            // 		System.out.println(true);
            		return true;
            	}
            }
            return false;
        }
    }
    

      

  • 相关阅读:
    关于影像颜色替换
    DevExpress TreeList控件的复选框
    深刻理解Vue中的组件
    【Vue】组件的基础与组件间通信
    vue语法糖
    vue中prop传值时加不加v-bind(冒号:)
    Vue从入门到实战
    vue-router实现原理
    Vue学习笔记——Vue-router
    Vue-router 学习笔记
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7053406.html
Copyright © 2011-2022 走看看