您的位置:首页 > 其它

【LeetCode】Jump Game && Jump Game II

2014-08-27 15:05 399 查看
1、Jump Game

Total Accepted: 17703 Total Submissions: 65204 My Submissions

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.

【解题思路】

1、题目大意应该是,初始位置为0,在i位置可以走的最大步数为A[i],问能不能走到A.length-1位置。

2、基本思想应该是,在每个位置判断可以走得最远的位置,以最远位置为基础,依次更新,直到达到指定位置为止。

Java AC 408ms

public class Solution {
    public boolean canJump(int[] A) {
        int n = A.length;
        if(n == 0){
        	return false;
        }
        int maxReach = 0;
        int i = 0;
        while (i < n && i <= maxReach) {
			maxReach = Math.max(i + A[i], maxReach);
			i++;
			if(maxReach >= n - 1){
				return true;
			}
		}
        return false;
    }
}


Python AC 312ms

class Solution:
    # @param A, a list of integers
    # @return a boolean
    def canJump(self, A):
    	if not A:
    		return False
    	n = len(A)
    	maxReach = 0
    	i = 0
    	while i < n and i <= maxReach:
    		maxReach = max(i+A[i], maxReach)
    		i += 1
    		if maxReach >= n - 1:
    			return True
    	return False


2、Jump Game II

Total Accepted: 15240 Total Submissions: 61956 My Submissions

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:

Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

【解题思路】

1、题目大意应该是,初始位置为0,在i位置可以走的最大步数为A[i],问走到A.length-1位置所需的最短步数。

2、基本思想应该是,在每个位置判断可以走得最远的位置,以当前可以达到最远位置为基础,计算下一步可以达到最远位置,如果比当前最远位置远,步数就+1,循环判断直到到达到指定位置为止。

Java AC 460ms

public class Solution {
	public int jump(int[] A) {
		int n = A.length;
		if (n == 0) {
			return 0;
		}
		int lastMaxReach = 0;
		int maxReach = 0;
		int i = 0;
		int minStep = 0;
		while (i < n && i <= maxReach) {
			if (i > lastMaxReach) {
				lastMaxReach = maxReach;
				minStep++;
			}
			maxReach = Math.max(i + A[i], maxReach);
			i++;
		}
		return maxReach >= n - 1 ? minStep : 0;
	}
}


Python AC 252ms

class Solution:
    # @param A, a list of integers
    # @return an integer
    def jump(self, A):
        if not A:
            return 0
        n = len(A)
        maxReach = 0
        lastMaxReach = 0
        i = 0
        count = 0
        while i < n and i <= maxReach:
            if i > lastMaxReach:
                lastMaxReach = maxReach
                count += 1
            maxReach = max(i + A[i], maxReach)
            i += 1
        return count if maxReach >= n - 1 else 0


这个题目有点拗口,具体的分析可以参考http://obcerver.com/post/view/p/25
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: