leetCode--- Jump Game II

来源:互联网 发布:mysql 索引 性能提升 编辑:程序博客网 时间:2024/06/04 18:26

一. 题目:Jump Game II

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

Note:
You can assume that you can always reach the last index.

二. 思路分析

          题目大意:给定一组非负整数,您最初位于数组的第一个索引处。 数组中的每个元素代表您在该位置的最大跳转长度。思路比较简单:也使用贪心,只不过是要记录当前一跳所能到达的最远距离、上一跳所能达到的最远距离,和当前所使用跳数就可以了代码如下:

public int jump(int[] A) {int jumps = 0, curEnd = 0, curFarthest = 0;for (int i = 0; i < A.length - 1; i++) {curFarthest = Math.max(curFarthest, i + A[i]);if (i == curEnd) {jumps++;curEnd = curFarthest;}}return jumps;}


原创粉丝点击