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

[LeetCode 45] Jump Game II

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

标签:java   leetcode   算法   

题目链接: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

标签:java   leetcode   算法   

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

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