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

LeetCode 55 _ Jump Game 跳跃游戏

时间:2019-03-29 20:59:27      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:位置   数字   its   int   一个   str   color   tput   描述   

Description:

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: [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: [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.

 

 

Solution: 

这道题让我们计算以数字的值为步数,是否能跳到数组的末位

 

其实这道题挺简单的,不知道为什么是medium?

核心思路就是引入一个变量temp,遍历数组内所有的数,将当前能跳的最长距离存入temp(每次将当前元素能跳的距离与之前最远距离相比,将较远的那个存入)

如果当前能跳的距离落在最后一个数或其后,表示能跳到,输出true

但是肯定不是一直将整个数组遍历完的,不能成功跳到数组的末位的情况,如题目描述中的第二种情况,具有什么特点呢?

我们来看题目中的例子 [3,2,1,0,4],当在3位时,之前最远能跳到的地方temp为3,当前位置能跳的距离也为3,判断的条件即为两个情况都该处不能向前跳且之前能跳的距离也不大于此处。

同时需要保证在循环的时候数组不越界,在循环时加入i<nums.length即可

 

这道题还有一个特殊情况,当输入的数组为单一个0时,实际上也是可以到达的,但是按正常的情况是不存在,因为它不能遍历到i++的情况,所以在最开始再考虑到这个情况即可

 

 

Code:

public boolean canJump(int[] nums) {
    
    int temp = 0,int i = 0;
    
    if (nums.length == 1 && nums[0] == 0){
        return true;
    }
    
	while (i < nums.length && (i + nums[i] > i || temp > i)) {
		temp = Math.max(temp, i + nums[i]);
		if (temp >= nums.length - 1){
			return true;
		}
		i++;
	}
	return i == nums.length;
}

  

 

提交情况:

Runtime: 2 ms, faster than 97.64% of Java online submissions for Jump Game.
Memory Usage: 40 MB, less than 83.19% of Java online submissions for Jump Game.

 

 

其他答案:

LeetCode中还有一个答案,它的思路和这个大致一样,但是用了temp作为遍历的指针,写出来更为简洁,同时不用考虑到特殊情况。代码如下:
public boolean canJump(int[] nums) {
    int i = 0;
    for (int reach = 0; i < nums.length && i <= reach; ++i){
        reach = max(i + nums[i], reach);
        return i == nums.length;
    }
}

  

LeetCode 55 _ Jump Game 跳跃游戏

标签:位置   数字   its   int   一个   str   color   tput   描述   

原文地址:https://www.cnblogs.com/zingg7/p/10623700.html

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