LeetCode算法题——Jump Game II

来源:互联网 发布:html5 css3 js pdf 编辑:程序博客网 时间:2024/06/10 15:10

题目概述

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

分析

这一题的难点在于每一步跳的次数不确定。为了不遗漏情况,我们应当遍历每一个点,利用贪心算法,检查每一个当前位置可以到达的点,选择最远的点,作为本次跳跃的目标点。代码如下:

int jump(vector<int> &nums) {    int steps = 0, start = end = 0, maxend = 0;    while (end < nums.size()) {        steps++;        for (int i = start; i <= end; i++) {            maxend = max(maxend, nums[i] + i); // 选择出跳跃的点        }        start = end + 1; // 从跳跃目标点的下一个点开始下一次循环        end = maxend; // 下一次跳跃最远能到达的点    }}

算法的时间复杂度为O(n),最坏的时候需要完整遍历数组;空间复杂度为O(1)。

总结

此题运用贪心算法,即提前算出下一步的下一步最远能跳到哪里,选择出最大值,决定出下一步跳跃的目标点。

原创粉丝点击