[leetcode]55. Jump Game(Java)

https://leetcode.com/problems/jump-game/#/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.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.


Java Code:

package go.jacob.day626;

public class Demo2 {
	/*
	 * 贪心算法的运用 Runtime: 8 ms.Your runtime beats 73.77 % of java submissions.
	 */
	public boolean canJump(int[] nums) {
		// 异常输入
		if (nums == null || nums.length < 1)
			return false;
		if (nums.length == 1)
			return true;
		int last = nums.length - 1;
		for (int i = nums.length - 2; i >= 0; i--) {
			if (i + nums[i] >= last)
				last = i;
		}
		return last == 0;
	}

}



你可能感兴趣的:(leetcode)