码迷,mamicode.com
首页 > 其他好文 > 详细

Jump Game —— LeetCode

时间:2015-05-19 12:37:23      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

题目大意:给定一个非负数组,每个元素代表可以跳的步数,判断从第一个能否跳到最后一个。

解题思路:暴力?二重循环,检查是否能到达最后一个元素。

     优化:时间O(n),空间O(1),一次遍历,首先记录当前可以覆盖的最大下标,遍历的时候如果从当前位置可以跳的更远则更新最大下标,如果当前位置不在最大下标覆盖范围内则return false,如果最大下标比数组更长,则return true。

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

 

Jump Game —— LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4514119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!