LeetCode week 7 : Jump Game II

来源:互联网 发布:格力大数据工程师 编辑:程序博客网 时间:2024/05/18 01:19

题目

地址:
https://leetcode.com/problems/jump-game-ii/description/
类别: Greedy
难度: Hard
描述:
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.

分析

题目要求根据非负数组中的元素进行跳跃,其中数组中的每个元素表示当前位置向后跳跃的最大步数,起点位于数组起始位置,需要求出最佳跳跃方式使得最终跳跃总次数最小,并输出总次数。

解决

思路一

贪心策略:从起点出发往后跳跃时,每次都选择跳到最有潜力的点,即跳到能往后跳最远的点。

代码实现

class Solution {public:    int jump(vector<int>& nums) {        int current = 0, current_max = nums[0], next_max = 0, next = 0, steps = 0;        if(nums.size() == 1) return 0;        while(current_max < nums.size()-1) {            for(int j = current + 1; j <= current_max && j <= nums.size()-1; j++) {                if(nums[j] + j >= next_max) {    //更新最有潜力的点                    next_max = nums[j] + j;                    next = j;                }            }            current = next;    //跳到该点            current_max = next_max;            steps++;        }        steps++;    //退出循环时还差一次跳跃才能到达最后点        return steps;    }};

思路二

转化为BFS:如2,3,1,1,4,2,6遍历顺序为2–3,1–1,4–2,6,则最终一共有几层即为跳跃次数。虽然思路不同,但最终代码是与上相似的。

代码实现

class Solution {public:    int jump(vector<int>& nums) {        int level = 0, current_level_max = nums[0] + 0, next_level_start = 1, next_level_max = 0;        if(nums.size() == 1) return 0;        while(current_level_max < nums.size() - 1) {            for(int next = next_level_start; next <= current_level_max; next++) {                if(nums[next] + next >= next_level_max) {                    next_level_max = nums[next] + next;                }            }            next_level_start = current_level_max;            current_level_max = next_level_max;            level++;        }        level++;        return level;    }};