LeetCode055——跳跃游戏

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82810039

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/jump-game/description/

题目描述:

知识点:贪心算法

思路:每次选取下一步位置时,选取所能达到最远的那个位置

本题的思路和LeetCode045——跳跃游戏II可以说是一模一样,但是需要注意以下几个细节。

(1)如果nums数组的长度为1,直接返回true。

(2)如果nums数组的长度不为1且nums数组的第一个元素为0,直接返回false。

(3)每次选取下一步索引时,都要判断下一步索引的值是否为0,如果为0,直接返回false。

JAVA代码:

public class Solution {

	public boolean canJump(int[] nums) {
        int n = nums.length;
        if(n == 1) {
        	return true;
        }
		int index = 0;
		if(nums[index] == 0) {
			return false;
		}
		while(index < n - 1) {
			int[] lengths = new int[nums[index]];
			if(index + nums[index] >= n - 1) {
				return true;
			}
			for (int i = index + 1; i <= index + nums[index]; i++) {
				lengths[i - index - 1] = i + nums[i];
			}
        	int max = 0;
        	for (int i = 0; i < lengths.length; i++) {
				if(lengths[i] > lengths[max]) {
					max = i;
				}
			}
        	index = max + index + 1;
        	if(nums[index] == 0) {
        		return false;
        	}
		}
		return true;
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82810039