首页 > 其他 > 详细

[LeetCode 45] Jump Game II

时间:2015-03-29 15:10:49      阅读:226      评论:0      收藏:0      [点我收藏+]

题目链接:jump-game-ii


相似题型: [LeetCode 55] Jump Game


/**
 * 
		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.)
 *
 */

public class JumpGameII {

//	91 / 91 test cases passed.
//	Status: Accepted
//	Runtime: 242 ms
//	Submitted: 0 minutes ago

	//时间复杂度O(n) 空间复杂度O(1)
	//题意是肯定能跳到终点,所以不需要考虑挑不到得情况
    public int jump(int[] A) {
		int jumps = 0; // 跳跃次数
		int choosedIndex = 0;
		while (choosedIndex < A.length - 1) {
			jumps++;
			if (choosedIndex + A[choosedIndex] >= A.length - 1) {
				return jumps;
			}
			int max = choosedIndex;
			for (int i = choosedIndex + 1; i <= choosedIndex + A[choosedIndex]; i++) {
				if (A[i] + i > A[max] + max) {
					max = i;
				}
			}
			choosedIndex = max;
		}
		return jumps;
    }
	public static void main(String[] args) {

	}

}


[LeetCode 45] Jump Game II

原文:http://blog.csdn.net/ever223/article/details/44726489

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!