[LeetCode 45]Jump Game II

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

相关文章:

你感兴趣的文章:

标签云: