国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

LeetCode-JumpGameII

2019-11-14 14:54:06
字體:
來源:轉載
供稿:網(wǎng)友

題目:

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

Subscribe to see which companies asked this question

思路:

1)用一個dp數(shù)組來記錄到達當前位置的最小步數(shù)

package dp;public class JumpGameII {    public int jump(int[] nums) {                int len = nums.length;        int[] dp = new int[len];        for (int i = 0; i < len; ++i)            dp[i] = Integer.MAX_VALUE;        dp[0] = 0;        // In order to save time, we don't visit the elements which already been visited.        int start = 1;        for (int i = 0; i < len - 1; ++i) {            start = go(i, nums[i], start, dp);        }                return dp[len-1];    }        // Get next start position.    private int go(int current, int step, int start, int[] dp) {        int i = start;        for (; i <= current + step && i < dp.length; ++i) {            if (dp[i] > dp[current] + 1)                dp[i] = dp[current] + 1;        }                return i;    }        public static void main(String[] args) {        // TODO Auto-generated method stub        int[] nums = { 2,3,1,1,4 };        JumpGameII j = new JumpGameII();        System.out.println(j.jump(nums));    }}

 

2)不用數(shù)組,就直接往前移動,第一次掃走一步能到的地方,第二次掃走二步能到的地方,在這個過程中,只要碰到了最后一個位置,就終止,證明是最小步數(shù)。

package dp;public class JumpGameII {    public int jump(int[] nums) {        int len;         if ((len = nums.length) == 1) return 0;        int count = 0;        int start = 0;        int end = 0;        while (end < len) {            int mostRight = 0;            ++count;            for (int j = start; j <= end; ++j) {                if (j + nums[j] >= len - 1)                    return count;                if (j + nums[j] > mostRight)                    mostRight = j + nums[j];            }                        start  = end + 1;            end = mostRight;        }                return count;    }        public static void main(String[] args) {        // TODO Auto-generated method stub        int[] nums = { 2,3,1,1,4 };        JumpGameII j = new JumpGameII();        System.out.println(j.jump(nums));    }}

 


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 巴马| 玛多县| 武平县| 盐边县| 盖州市| 盐山县| 无锡市| 安仁县| 中宁县| 郴州市| 岳阳县| 文山县| 彭州市| 余姚市| 敦煌市| 永寿县| 阜阳市| 景泰县| 章丘市| 奎屯市| 交口县| 汶上县| 丽江市| 司法| 佳木斯市| 岑巩县| 宁南县| 蒙山县| 漯河市| 长岛县| 怀安县| 盐源县| 永年县| 山丹县| 辽宁省| 柘城县| 绥滨县| 九江县| 宜章县| 沂南县| 涞水县|