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], returntrue.

A = [3,2,1,0,4], returnfalse.

解题思路:

  1. 这道题的意思是每个元素代表可以走的最大步数,能走到数组的结尾就返回 true,否则返回 false;
  2. 先说一下我的错误思路,我考虑了当前元素是 0 的情况,在这里其实不用考虑的
  3. 这道题考察的点是贪心算法,即每次都要走到最远处,因为既然能够走到最远处去,那么它的近处也是可以访问的

代码如下:

    public boolean canJump(int[] A) {
       int len = A.length;
       int temp = 0;

	// temp 表示是否可以到达当前的 i 位置
       for(int i = 0; i < len; i++){
	   
	   // 如果能够到达当前的位置 i ,而且当前位置能够达到的最远距离大于 temp,就对 temp 值进行更换
           if(temp >= i){
               if(A[i] + i > temp){
                   temp = A[i] + i;
               }
           }
       }

       if(temp >= len - 1) return true;
        else return false;
    }

转载于:https://my.oschina.net/happywe/blog/3086423

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值